在javascript中实现扩展方法

在javascript中实现扩展方法

问题描述:

通过查看BackboneJS的代码,我对扩展实现感兴趣。当我试图让自己陷入困境时。我的代码如下。在javascript中实现扩展方法

var extend = function(child) { 
    var base = this; 

    if(child) { 
    for(var prop in child) { 
     base[prop] = child[prop]; 
    } 
    } 

    return base; 
}; 

var Test = Mod.Test = function() { 
    this.data = {}; 
} 

Test.prototype.set = function(key, value) { 
    this.data[key] = value; 
} 

Test.prototype.get = function(key) { 
    return this.data[key]; 
} 

Test.extend = extend; 

当我尝试这样我不能够连接方法打招呼Mod.Test

var testObj = new Mod.Test.extend({ 
hello : function() { 
    console.log('hello'); 
} 
}); 

这怎么可能。它是如何在backbonejs中实现的。

+0

@muistooshort感谢您的答复..但是当我尝试testObj.get('xyz')其未定义.. – 2013-03-06 18:56:15

Backbone的扩展方法接受两个参数 - 实例属性和静态属性。第一个被复制到正在创建的实例中,第二个被分配给实例的原型。通常你应该调用没有新的运营商的扩展方法,但在这种情况下,这里是你的代码的工作版本:

var extend = function(child) { 
    var base = this; 

    if(child) { 
    for(var prop in child) { 
     base[prop] = child[prop]; 
    } 

    for(var prop in child) { 
     base.prototype[prop] = child[prop]; 
    } 
    } 



    return base; 
}; 

var Test = Backbone.Model.Test = function() { 
    this.data = {}; 
} 

Test.prototype.set = function(key, value) { 
    this.data[key] = value; 
} 

Test.prototype.get = function(key) { 
    return this.data[key]; 
} 

Test.extend = extend; 

然后:

Test = Backbone.Model.Test.extend({ 
    hello : function() { 
    console.log('hello'); 
    } 
}); 
var testObj = new Test;