• 欢迎访问少将全栈,学会感恩,乐于付出,珍惜缘份,成就彼此、推荐使用最新版火狐浏览器和Chrome浏览器访问本网站。
  • 吐槽,投稿,删稿,交个朋友,商务沟通v:ai_draw
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏少将全栈吧

植树节练习JS语言之魂-原型模式

Web前端 admin 7年前 (2017-03-12) 2243次浏览 已收录 0个评论 扫描二维码

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

/**
 * Created by whatled on 2017/3/12.
 */
// 图片轮播类
var LoopImages = function (imgArr, container) {
    this.imagesArray = imgArr;  // 轮播图片数组
    this.container = container; // 轮播图片容器
};
LoopImages.prototype = {
    // 创建轮播图片
    createImage: function () {
        console.log(’LoopImages createImage function’);
    },
    // 切换下一张图片
    changeImage: function () {
        console.log(’LoopImages changeImage function’);
    }
};
// 上下滑动切换类
var SlideLoopImg = function (imgArr, container) {
    // 构造函数继承图片轮播类
    LoopImages.call(this, imgArr, container);
};
SlideLoopImg.prototype = new LoopImages();
// 重写集成的切换下一张图片方法
SlideLoopImg.prototype = function () {
    console.log(’SlideLoopImg changeImage function’);
};
// 渐隐切换类
var FadeLoopImg = function (imgArr, container, arrow) {
    LoopImages.call(this, imgArr, container);
    // 切换箭头私有变量
    this.arrow = arrow;
};
FadeLoopImg.prototype = new LoopImages();
FadeLoopImg.prototype.changeImage = function () {
    console.log(’FadeLoopImg changeImage function’);
};
LoopImages.prototype.getImageLength = function () {
    return this.imagesArray.length;
};
FadeLoopImg.prototype.getContainer = function () {
    return this.container;
};
// 测试用例
var fadeImg = new FadeLoopImg([’01,jpg’,
    ’02.jpg’,
    ’03.jpg’,
    ’04.jpg’], ’slide’, [
    ’left.jpg’,
    ’right.jpg’
]);
console.log(fadeImg.container); // slide
fadeImg.changeImage();    // fadeLoopImg ChangeImage function
console.log(fadeImg.getImageLength());
console.log(fadeImg.getContainer());
// 对模版引用类型的属性实质上进行了浅复制
function prototypeExtend() {
    var F = function () {
        },
        args = arguments,
        i = 0,
        len = args.length;
    for (; 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(’跳跃动作’);
    }
});
// 测试
penguin.swim();     // 游泳速度20
penguin.run(10);    // 奔跑速度10
penguin.jump();     // 跳跃动作

喜欢 (0)
[🍬谢谢你请我吃糖果🍬🍬~]
分享 (0)
关于作者:
少将,关注Web全栈开发、项目管理,持续不断的学习、努力成为一个更棒的开发,做最好的自己,让世界因你不同。
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址