Javascript设计模式之创建对象的灵活性

传统的

/* Anim class */
var Anim = function () {};
Anim.prototype.start = function () {
    console.log("start");
}

Anim.prototype.stop = function () {
    console.log("stop");
}

/* Usage */
var myAnim = new Anim();
myAnim.start();
myAnim.stop();

 json方式

/* Anim class */
var Anim = function () {};
Anim.prototype = {
    start:function () {
        console.log("start");
    },
    stop:function () {
        console.log("stop");
    }
}

/* Usage */
var myAnim = new Anim();
myAnim.start();
myAnim.stop();

给Function定义一个方法

Function.prototype.method = function (name,fn) {
    this.prototype[name] = fn;
}

var Anim = function () {};
Anim.method('start',function(){
    console.log("start");
});
Anim.method('stop',function(){
    console.log("stop");
});

var myAnim = new Anim();
myAnim.start();
myAnim.stop();

升级Function方法,可以连续使用

Function.prototype.method = function (name,fn) {
    this.prototype[name] = fn;
    return this; // 返回对象本身
}

var Anim = function () {};
Anim.method('start',function(){
    console.log("start");
}).method('stop',function(){
    console.log("stop");
});

var myAnim = new Anim();
myAnim.start();
myAnim.stop();

本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6196914.html,如需转载请自行联系原作者

    原文作者:javascript设计模式
    原文地址: https://yq.aliyun.com/articles/340305
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞