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();


posted @ 2016-12-19 11:46  TBHacker  阅读(259)  评论(0编辑  收藏  举报