javascript设计模式---原型模式

用原型实例指向创建对象的类,可以共享原型中的方法和属性。

var LoopImages = function(imgArr,container){
    this.imageArray = imgArr
    this.container = container
}
LoopImages.prototype = {
    createImage : function () {
        console.log('Loop Images create Image function')
    },
    changeImage(){
        console.log('Loop Images change Image function')
    }
}
var SlideLoopImg = function (imgArr,container) {
    LoopImages.call(this,imgArr,container)
}

var FadeLoopImg = function(imgArr,container,arrow){
    LoopImages.call(this,imgArr,container)
    this.arrow = arrow //arrow为此类私有属性
}
SlideLoopImg.prototype = new LoopImages()  //{imageArray,container}   这个对象的原型中有方法

SlideLoopImg.prototype.changeImage = function(){
    console.log('a')  //重写原型继承的方法
}

var slide = new SlideLoopImg(['a','b','c'],'div1')
slide.changeImage() //a

原型继承

当创建一个实例对象的构造函数比较复杂或者需要通过创建多个对象来实现,可以对这些对象属性或者方法进行复制

/* 基于已经存在的模板对象克隆出新对象的模式  */
function prototypeExtend(){
    var F = function(){}
    args = arguments;
    for(let i = 0;i<args.length;i++){
        for(let j in args[i]){
            F.prototype[j] = args[i][j]
        }
    }   
    return new F();
}

var penguin = prototypeExtend({
    speed:20, 
    swim:function(){
        console.log('游泳速度'+this.speed)
    },
    run:function(speed){
        console.log('跑步速度'+speed)
    },
    jump:function(){
        console.log('游泳速度')
    }
},{
    sleep:function(){
        console.log('睡觉了')
    }
})
penguin.swim()
penguin.run(30)
penguin.sleep()

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