我尝试将 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#call
或 Function#apply
使用特定的 this
值调用函数,但您可能不想 在您的场景中。
有关此
的更多信息(在我的博客上):
- Mythical methods
- You must remember
this
(我需要更新这个来讨论 ES6 箭头函数)
回复您的评论:
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/