javascript - jQuery $.extend 命名空间

标签 javascript jquery

如何使用嵌套命名空间扩展对象原型(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/

相关文章:

javascript - 数组中相同的值必须放在一起

javascript - Controller 范围内的变量

javascript - 如何向存储在组件状态中的空对象添加新属性?

javascript - 在 geckoWebBrowser 中模拟 HTML 文本框中的击键

javascript - 从 mysql 和 php 检索 json 数据到 jquery

javascript - jQuery setTimeout 不停止函数执行

php - 如何通过 php 页面检索数据库值到 jquery 自动完成框

javascript - 如何在 Observable 方法中顺序调用异步函数?

javascript - 如何调试 jQuery 嵌套可排序可拖动元素?

jquery - 使用 jquery ajax 上传文件 - null 问题