javascript - 从对象的内联函数中访问 this

标签 javascript function object inline 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

    }

}

如何访问 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/

相关文章:

javascript - 使用 Qt.include(...) 导入 js 文件时缺少 QtCreator 智能感知

javascript - jQuery - fadeTo() - 我如何让它在每次调用事件时越来越淡?

javascript - Angular Directive(指令) ng-repeat 范围和服务

swift - 在下面的特定示例中,我将如何创建一个函数来删除重复代码?

javascript - 如何循环遍历对象的对象?

javascript - JS 数组到对象的数组

javascript - 在D3中,如何向geojson要素集合中的要素添加标签

javascript - 复制不带属性的函数引用

c# - 创建的对象能够访问创建它的对象的成员

javascript - 编程新手,不明白为什么这个因子计算器不起作用