2010-08-28 109 views
11

我很难从对象方法内的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方法中。

+0

[为什么不能访问'this'关键字? - jQuery](http://stackoverflow.com/questions/3323189/why-doesnt-this-closure-have-access-to-the-this-keyword-jquery) – 2010-08-28 12:15:04

回答

30

一种常用的方法是将this分配给你想要的局部变量。

init: function() { 
    var _this = this; 
    this.testObject.submit(function() { 
     console.log(_this.testVariable); // outputs testVariable 
    }); 
} 
+1

哦,“this”的赋值是在init功能 - 当然......老鼠! 这就是我想要做的,但在匿名函数中分配它... 感谢您的帮助! – Matt 2010-08-28 12:25:44

+0

现在我觉得自己是世界上最愚蠢的人 - – kurumkan 2016-11-01 10:49:50

0

“此”变量绑定时动态函数— 任何功能,无论它被定义—的是称为

没有看到“submit”函数应该做什么,或者它应该被使用的地方,很难说如何改变它。有一两件事你可以做的是确定“提交”在你的“初始化”功能:

init: function() { 
    // whatever 
    var instance = this; 
    instance.submitForm = function() { 
    console.log(instance.testVariable); 
    // ... 
    }; 
} 

只要“初始化”与“此”设置为你的对象的一个​​实例最初称,你应该好。

0

您只能从对象的上下文中访问oThis变量,因为您处于另一个函数内部而丢失了该变量。或者通过实例化一个新对象。这样

var testInstance = new testObject(); 

然后,你可以通过访问oThis:

testInstance.oThis; 

但是这将是多余的

我会尝试这样马特:

init: function(){ 

var self = this; // this allows you to access the parent object from different contexts 

this.testObject.submit(function(){ 

    console.log(self.testVariable); 

} 
5

你可以也使用ES6箭头功能来做到这一点:

init: function(){ 
    this.testObject.submit(() => { 
     console.log(this.testVariable); 
    } 
} 

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