我很难从对象方法内的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'关键字? - jQuery](http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery) – 2010-08-28 12:15:04