我很难在对象方法中的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
}
}
Run Code Online (Sandbox Code Playgroud)
如何this.testVariable从提交功能中进行访问?我也使用jQuery,如果这有所不同.
我想知道这是否是最好的方法 - 也许我应该作为一个单独的函数提交,然后引用内联,如:
init : function(){
this.testObject.submit = this.submitForm;
},
submitForm : function(){
// do validation here
console.log(this.testVariable) // outputs testvariable
.
.
.
return valid;
}
Run Code Online (Sandbox Code Playgroud)
但这似乎也没有用 - 我想我现在只想在我的init方法中保持提交函数内联.
我正在研究一个项目一段时间,试图找出我做错了什么,当我最终将"错误"缩小到下面的代码不能按预期工作的事实时:
function Alpha()
{
this.onion = 'onion';
function Beta()
{
alert(this.onion);
}
Beta();
}
alpha1 = new Alpha();
// Alerts 'undefined'
Run Code Online (Sandbox Code Playgroud)
但是,如果我将代码更改为:
function Alpha()
{
var self = this;
this.onion = 'onion';
function Beta()
{
alert(self.onion);
}
Beta();
}
alpha1 = new Alpha();
// Alerts 'onion'
Run Code Online (Sandbox Code Playgroud)
它像我期望的那样工作.在浪费了我生命中的大部分时间之后,任何人都可以解释为什么它会像这样工作吗?