我在对象方法中的 javascript 内联函数中引用“this”时遇到了困难。
var testObject = {
oThis : this,
testVariable : "somestring",
init : function(){
console.log(this.testVariable); // outputs testVariable as expected
this.testObject.submit(function(){
var anotherThis = this;
console.log(this.testVariable) // undefined
console.log(oThis.testVariable) // undefined
console.log(testObject.testVariable) // outputs testVariable
console.log(anotherThis.testVariable) // undefined
}
}
如何访问
this.testVariable
从提交功能中?我也在使用 jQuery,如果这有所作为的话。
我想知道这是否是最好的方法——也许我应该将提交作为一个单独的函数,然后引用该内联函数,例如:
init : function(){
this.testObject.submit = this.submitForm;
},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable
.
.
.
return valid;
}
但这似乎也不起作用 - 我想我只想将提交函数内联在我的
init
中。暂时的方法。
最佳答案
一种常见的方法是分配 this
你想要一个局部变量。
init: function() {
var _this = this;
this.testObject.submit(function() {
console.log(_this.testVariable); // outputs testVariable
});
}
关于javascript - 从对象的内联函数中访问 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3590685/