如何使用嵌套命名空间扩展对象原型?
http://jsfiddle.net/2t5314nu/2/
我希望能够调用像this.nested.method这样的Obj.prototype中的嵌套方法,并且能够以this.prop的形式访问nested中的原型属性和方法。
但是,当我使用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();发布于 2014-11-10 08:34:46
您发布的代码中未定义this.nested。在调用extend时为嵌套对象命名,以便将其添加到特定的点,而不是覆盖:
嵌套( true,Obj.prototype,{$.extend:Obj.prototype })
发布于 2014-11-10 10:38:28
您可能不知道JavaScript中的this是什么,它是调用对象,所以this是方法之前的对象:
peter.doSomothing();//this in doSomething is peter
peter.nested.doSomething();//this in doSomething is nested
new Person();//when new is used this is the Person instance to be created您可以在调用嵌套的方法时使用.call或.apply来定义调用对象(如注释中所述)。
function Obj() {
this.prop = 'val';
this.init();
}
Obj.prototype = {
init: function() {
console.log('in Obj.prototype.init: ' + this.prop);
nested.init.call(this);
nested.method.call(this);
}
};
var nested = {
init: function() {
console.log('nested init');
console.log('prop in nested init: ' + this.prop);
},
method: function() {
console.log('nested method');
console.log('prop in nested method: ' + this.prop);
}
};
var o = new Obj();或者,您可以让Obj实例具有对Obj的引用的嵌套实例:
var Nested = function Nested(objInstance){
this.objInstance = objInstance;
};
Nested.prototype.init = function init(){
console.log('init in nested',this.objInstance);
this.method();
};
Nested.prototype.method = function method(){
console.log('method in nested',this.objInstance);
};
var Obj = function Obj(){
this.nested = new Nested(this);
this.prop='prop of Obj';
};
Obj.prototype.init = function init(){
console.log('init in Obj',this);
this.nested = new Nested(this);
};
var objInstance = new Obj();
objInstance.init();
objInstance.nested.init();有关构造函数和原型的更多信息,请单击此处:https://stackoverflow.com/a/16063711/1641941
https://stackoverflow.com/questions/26834990
复制相似问题