首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery $.extend命名空间

jQuery $.extend命名空间
EN

Stack Overflow用户
提问于 2014-11-10 08:24:05
回答 2查看 73关注 0票数 1

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

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

我希望能够调用像this.nested.method这样的Obj.prototype中的嵌套方法,并且能够以this.prop的形式访问nested中的原型属性和方法。

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

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

代码语言:javascript
复制
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();
EN

回答 2

Stack Overflow用户

发布于 2014-11-10 08:34:46

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

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

票数 0
EN

Stack Overflow用户

发布于 2014-11-10 10:38:28

您可能不知道JavaScript中的this是什么,它是调用对象,所以this是方法之前的对象:

代码语言:javascript
复制
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来定义调用对象(如注释中所述)。

代码语言:javascript
复制
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的引用的嵌套实例:

代码语言:javascript
复制
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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26834990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档