2013-03-06 60 views
0

通過查看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

回答

2

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;