JavaScript在不同上下文中的"this" [英] JavaScript 'this' in different context
问题描述
我正尝试如下创建JavaScript对象.
I am trying to create a JavaScript object as follows.
var MyObject = function (parameters) {
this.parameters = parameters;
parameters.userFunction(this.MyObjectCallback);
}
MyObject.SOME_STATIC_VARIABLE = 21;
MyObject.prototype = {
myObjectCallback: function() {
console.log(this);
}
}
MyObject
对象将接受将传递处理程序的userFunction.用户函数将执行一些逻辑,并将结果传递回实例,例如:
The MyObject
object will accept a userFunction to which it will pass a handler. The user function will do some logic and pass the result back to the instance, for example:
new MyObject({userFunction: function(callback) {
$.post(
'http://localhost/~knyttl/source.php',
{},
callback,
'json');,
}});
不幸的是,即使正确地调用了callback
,但this
还是得到了JQuery
对象的实例,而不是我想要的MyObject
实例.最后,我无法保留MyObject
实例.
Unfortunately, even though the callback
is properly called, this
gets an instance of the JQuery
object and not of the MyObject
instance as I would like. To conclude, I can not manage to keep the MyObject
instance.
我什至不确定这是否是创建JavaScript对象的正确方法.任何建议,我将不胜感激.
I am not even sure, whether this is a correct way of creating JavaScript objects. I will be grateful for any suggestion.
推荐答案
您可以使用.bind
绑定特定的this
值.我也更正了My
的大写字母.
You can bind a specific this
value using .bind
. Also I corrected the capitalizing of My
.
parameters.userFunction(this.myObjectCallback.bind(this));
当调用诸如a.b()
之类的函数时,则在b
,this === a
中.但是,如果您不直接调用它,而仅传递该函数(例如a.b
),然后再调用它,则此绑定会丢失.
When you call a function like a.b()
, then inside b
, this === a
. However, if you do not directly call it but only pass the function (like a.b
) and call it later, this binding is lost.
.bind
返回一个新函数,该函数现在将jQuery ajax结果接收为this
.但是,它将忽略该内容,并使用预定义的(绑定)this
调用myObjectCallback
.
.bind
returns a new function which now receives the jQuery ajax result as this
. However, it ignores that and calls myObjectCallback
with the predefined (bound) this
.
.bind
在较旧的浏览器上不可用,但有垫片可用.
.bind
is not available on older browsers but there are shims available.
这篇关于JavaScript在不同上下文中的"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!