JavaScript设计模式 (1) 原型模式

原型模式(Prototype):用原型实例指向创建类对象,使用于创建新对象的类共享原型对象的属性以及方法。

 1 //图片轮播类
 2 var LoopImages = function (imgArr, container) {
 3     this.imagesArray = imgArr;//轮播图片数组
 4     this.container = container;//轮播图片容器
 5 };
 6 
 7 
 8 LoopImages.prototype = {
 9     //创建轮播图片
10     createImage: function () {
11         console.log('LoopImages createImage function');
12     },
13     //切换下一张图片
14     changeImage: function () {
15         console.log('LoopImages changeImage function');
16     }
17 };
18 
19 //上下滑动切换类
20 var SlideLoopImg = function (imgArr, container) {
21     //构造函数继承图片轮播类
22     LoopImages.call(this, imgArr, container);
23 };
24 SlideLoopImg.prototype = new LoopImages();
25 //重写继承的切换下一张图片方法
26 SlideLoopImg.prototype.changeImage = function () {
27     console.log('SlideLoopImg changeImage function');
28 };
29 
30 //渐隐切换类
31 var FadeLoopImg = function (imgArr, container,arrow) {
32     //构造函数继承图片轮播类
33     LoopImages.call(this, imgArr, container);
34     this.arrow = arrow;
35 };
36 FadeLoopImg.prototype = new LoopImages();
37 //重写继承的切换下一张图片方法
38 FadeLoopImg.prototype.changeImage = function () {
39     console.log('FadeLoopImg changeImage function');
40 };

原型继承

    原型模式更多的是用在对象的创建上。比如创建一个实例对象的构造函数比较复杂,或者耗时比较长,或者通过创建多个对象来实现。此时我们最好不要用new关键字去复制这些基类,但可以通过对这些对象属性或者方法进行负责来创建实例,这是原型模式的最初思想。如果涉及多个对象,我们也可以通过原型模式来实现对新对象的创建。那么首先要有一个原型模式的对象复制方法。

/**********
*基于已经存在的模版对象克隆出新对象的模式
*arguments[0],arguments[1],arguments[2]:参数1,参数2.参数3表示模版对象
*注意。这里对模版引用类型on个的属性实质上进行了浅复制(引用类型属性共享),当然根据需求可以自行深复制。
******/
function prototypeExtend() {
    var F = function () { },
        args = arguments,
        i = 0,
        len = args.length;
    for (var i = 0; i < len; i++) {
        //遍历每个模版对象中的属性
        for (var 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('跳跃动作');
    }
});

既然通过prototypeExtend创建的是一个对象,我们就无需再用new去创建新的实例对象,我们可以直接使用这个对象。

penguin.swim();//游泳速度 20
penguin.run(10);//奔跑速度 10
penguin.jump();//跳跃动作

  学习《JavaScript 设计模式》 中。

posted @ 2016-03-30 21:34  暗夜苹果  阅读(191)  评论(0编辑  收藏  举报