javascript设计模式——原型模式

摘要:原型模式,就是将原型对象指向创建对象的类,使这些类共享原型对象的方法和属性。

需求:创建一个焦点图,焦点图需要实现上下滑动和淡入淡出效果。

直接调用父类方法

    // 使用该方式创建,会造成每次创建子类的是有,都要实例化父类,造成性能问题
    var LoopImages = function(imgArr, container) {
      this.imageArray = imgArr
      this.container = container
      this.createImage = function() {}
      this.changeImage = function() {}
    }

    var SlideLoopImg = function (imgArr, container) {
      LoopImages.call(this, imgArr, container)
      this.changeImage = function () {
        console.log('slideLoopImg changeImage function')
      }
    }

    var FadeLoopImg = function (imgArr, container, arrow) {
      LoopImages.call(this, imgArr, container)
      this.arrow = arrow
      this.changeImage = function () {
        console.log('FadeLoopImage changeImage function')
      }
    }

    var fadeImg = new FadeLoopImg(['a.jpg', 'b.jpg'], 'slide', ['left.jpg', 'right.jpg'])

使用原型链共享父类方法和属性

    var LoopImages = function(imgArr, container) {
      this.imagesArray = imgArr
      this.container = container
    }
    LoopImages.prototype = {
      createImage: function () {
        console.log('LoopImages createImage funciton')
      },
      changeImage: function () {
        console.log('LoopImage changeImage function')
      }
    }

    var SlideLoopImg = function (imgArr, container) {
      LoopImages.call(this, imgArr, container)
    }

    SlideLoopImg.prototype = Object.create(LoopImages.prototype)
    SlideLoopImg.prototype.changeImage = function () {
      console.log('SlideLoopImg changeImage function')
    }
    
    var FadeLoopImg = function (imgArr, container, arrow) {
      LoopImages.call(this, imgArr, container)
      this.arrow = arrow
    }
    FadeLoopImg.prototype = Object.create(LoopImages.prototype)
    FadeLoopImg.prototype.changeImage = function() {
      console.log('FadeImage chagneImg function')
    }
    var fadeImg = new FadeLoopImg(['01.jpg','02.jpg','03.jpg'], 'slide', ['left.jpg', 'right.jpg'])
    console.log(fadeImg.container) // slide
    fadeImg.changeImage()  // FadeImage chagneImg function

你可能感兴趣的:(javascript设计模式——原型模式)