gpt4 book ai didi

javascript - 在javascript中实现扩展方法

转载 作者:行者123 更新时间:2023-12-02 18:56:50 24 4
gpt4 key购买 nike

通过查看 BackboneJS 的代码,我对扩展实现很感兴趣。当我尝试自己做时,我被困住了。我的代码如下。

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;

当我这样尝试时,我无法将 hello 方法附加到 Mod.Test

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

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

最佳答案

Backbone 的扩展方法接受两个参数 - 实例属性和静态属性。第一个被复制到正在创建的实例,第二个被分配给实例的原型(prototype)。通常,您应该在不使用 new 运算符的情况下调用扩展方法,但在本例中,这是代码的工作版本:

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;

关于javascript - 在javascript中实现扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15254894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com