javascript - jQuery 使用 Prototype 对象扩展对象

标签 javascript jquery

我尝试将 Prototype 对象聚合为 JavaScript 普通对象:

var ModuleA = function( data ) {
    this.data = data;
};

ModuleA.prototype.funcA = function() {
    alert( JSON.stringify( this ) );
}

var myMainObject = { 
    list: []
};

$.extend( myMainObj <--------- ???ect, new ModuleA( 'Haha' ) );

myMainObject.funcA();

现在,myMainObject 将具有 data 属性和 funcA 函数,因为我合并到 myMainObject

当我执行myMainObject.funcA时,this参数实际上是myMainObject!

据我了解,当new一个Prototype对象时,该函数将绑定(bind)到用new创建的对象并传递给构造函数。

但是使用jQuery扩展后,this参数不是新对象,而是指向myMainObject,这让我很困惑。

有什么想法吗?

最佳答案

When I execute myMainObject.funcA, the this arguments actually is myMainObject !!!

对。这就是 this 在 JavaScript 中的工作原理。这个表达式:

myMainObject.funcA();

查找 myMainObject 上的 funcA 属性,获取函数引用,然后调用该函数,并在调用期间设置 this从中获取函数的对象 (myMainObject)。这是 this 的正常分配方式。

如果您希望 this 成为其他内容,可以使用 Function#bind 创建一个包含 this 的函数,或者Function#callFunction#apply 使用特定的 this 值调用函数,但您可能不想 在您的场景中。

有关的更多信息(在我的博客上):

<小时/>

回复您的评论:

My actual intention is to let ModuleA functions has its own scope without jumble up with the myMainObject attribute

然后不要将 ModuleA 混入 myMainObject 中。听起来您想要组合:

var myMainObject = { 
    list: [],
    moda: new ModuleA()
};

myMainObject.moda.funcA();

关于javascript - jQuery 使用 Prototype 对象扩展对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421733/

相关文章:

javascript - 从 URL 获取数据并防止自动重定向(附加 SDK Mozilla)

javascript - 将 <a> 标记的 href 值链接到另一个 html 页面

javascript - 你如何测试 $(document).ready() 中定义的函数

javascript - $ ('#' ) 和 document.getElementById() 有什么区别?

javascript - 如何使用 jQuery 在 iPhone Safari 上创建照片 slider ?

javascript - 从自定义事件返回 false 会在新的 jquery 版本中产生错误

javascript - 为什么我的 Handlebars #each 循环中的 @first 总是 false?

javascript - jquery计算选中复选框旁边的html值

javascript - HTML5 Canvas 渲染/缓存问题

jquery - <select> 事件 'change' 未在 'selectedIndex' 更改时触发