【发布时间】:2011-04-05 04:15:01
【问题描述】:
我在对象方法中的 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,如果这有影响的话。
我想知道这是否是最好的方法 - 也许我应该将 submit 作为一个单独的函数,然后引用该内联函数,例如:
init : function(){
this.testObject.submit = this.submitForm;
},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable
.
.
.
return valid;
}
但这似乎也不起作用 - 我想我现在只想将提交函数内联在我的 init 方法中。
【问题讨论】:
标签: javascript function object inline this