从对象的内联函数中访问它

Mat*_*att 18 javascript inline function object this

我很难在对象方法中的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方法中保持提交函数内联.

Mat*_*nen 38

一种常见的方法是将this您想要的分配给局部变量.

init: function() {
   var _this = this;
   this.testObject.submit(function() {
        console.log(_this.testVariable); // outputs testVariable 
   });
}
Run Code Online (Sandbox Code Playgroud)


jit*_*tin 7

您也可以使用ES6箭头功能执行此操作:

init: function(){
    this.testObject.submit( () => {
        console.log(this.testVariable);
    }
}
Run Code Online (Sandbox Code Playgroud)

箭头函数捕获this封闭上下文的值,避免分配this给新变量或使用绑定函数.