【问题标题】:"this" keyword in JS - I'm confused [duplicate]JS中的“this”关键字-我很困惑[重复]
【发布时间】:2014-08-04 13:10:37
【问题描述】:

我对 JS 中的 this 关键字感到困惑,如下所示。为什么 this.this_ 在第 3 行中未定义)?有什么简单的说明吗?在第 2 行)this 指向 Window 对象 - 我很惊讶,但我可以接受 - 为什么会这样?唯一对我有用的是使用this2_ 变量,但我认为这并不优雅。如何以良好、优雅的方式使用this 始终工作并指向O 对象?

var a = function(callback){
    callback('test');
};
var O = function(){
    this.val = 'abc';
    var this2_ = this;
    this.this_ = this;

    this.f = function(){
        console.log(this);           // (1) this -> O object, that's OK
        a(function(){           
            console.log(this);       // (2) this -> Window object
            console.log(this.this_); // (3) this.this_ -> undefined
            console.log(this2_);     // (4) this2_ -> O object
        });
    }
};
var o = new O();
o.f();

【问题讨论】:

  • 您为什么要这样做?为什么因为 this 在该函数中不是 this。你的 cmets 表明了这一点。
  • var this2_ = this; 是这样做的方法。原因是另一个函数中的范围发生了变化,this 变得不同了。使用var this2_ = this,您将其放入内部函数范围内的本地变量中。

标签: javascript oop javascript-objects


【解决方案1】:

不建议“管理”this,因为它会在不同的范围内发生变化。在这种情况下,当您尝试在新函数中获取值时,您处于新范围内,而this 指的是窗口对象。

您应该使用一个新变量,并尽量不要将东西附加到this。仅出于只读原因使用它

注意:这并非不可能(例如 jQuery 对this 进行了很好的管理),但不建议这样做。

所以在你的情况下,你可以这样做:

var O = function(){
    var this2;
    this2.this_ = this;
    this2.val = 'abc';

    this.f = function(){
        a(function(){       
            console.log(this2.val);   // (1) 'abc' 
            console.log(this2.this_); // (2) O object
        });
    }
};

【讨论】:

  • 谢谢。我将使用var this_ = this; 作为对象中的第一行代码,并使用this_ 访问“所有地方”中的对象实例。这是我认为最简单的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 2017-09-07
  • 2014-09-28
  • 2019-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多