gpt4 book ai didi

javascript - jQuery $.extend 命名空间

转载 作者:行者123 更新时间:2023-11-28 10:54:26 25 4
gpt4 key购买 nike

如何使用嵌套命名空间扩展对象原型(prototype)?

http://jsfiddle.net/2t5314nu/2/

我希望能够从 Obj.prototype 调用嵌套方法(如 this.nested.method),并能够从 nested 访问原型(prototype)属性和方法this.prop

但是,当我使用 jQuery $.extend 时,nested 中的 init 方法会覆盖 Obj.prototype< 中的方法。事实上,Obj.prototype.init 从未被调用过。

我想避免使用 nested.init 覆盖 Obj.prototype.init。我可以使用 $.extend 以外的其他内容。

function Obj() {
this.prop = 'val';
this.init();
}

Obj.prototype = {
init: function() {
console.log('object init');
console.log('prop in object init: ' + this.prop);
$('#object-init').text('object init');
this.nested.init();
this.nested.method();
}
};

var nested = {
init: function() {
console.log('nested init');
console.log('prop in nested init: ' + this.prop);
$('#nested-init').text('nested init');
},
method: function() {
console.log('nested method');
console.log('prop in nested method: ' + this.prop);
$('#nested-method').text('nested method');
}
};

$.extend(true, Obj.prototype, nested);

new Obj();

最佳答案

this.nested 在您发布的代码中未定义。当您调用扩展时为嵌套对象命名,以便将其添加到特定位置而不是覆盖:

$.extend( true, Obj.prototype, { 嵌套: 嵌套 })

关于javascript - jQuery $.extend 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834990/

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