【问题标题】:this keyword inside an object's function对象函数中的 this 关键字
【发布时间】:2016-06-20 14:24:35
【问题描述】:

我不明白下面代码中的 var self = this;。我知道“this的值,当在函数中使用时,是“拥有”该函数的对象。”。然后对象函数内的this关键字指的是该对象,对吧?但是下面代码的cmets却说相反那个。

我很困惑为什么我们不能在下面的代码中在对象的函数中使用这个关键字?这在下面的代码中指的是什么?

var util = require('util');
var EventEmitter = require('events').EventEmitter;

// @station - an object with `freq` and `name` properties
var Radio = function(station) {

    // we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // !!!! -> using `this` in the setTimeout functions will refer to those funtions, not the Radio class
    var self = this;

    // emit 'close' event after 5 secs
    setTimeout(function() {
        self.emit('close', station);
    }, 5000);

    // EventEmitters inherit a single event listener, see it in action
    this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });
};

// extend the EventEmitter class using our Radio class
util.inherits(Radio, EventEmitter);

// we specify that this module is a refrence to the Radio class
module.exports = Radio;

我阅读了类似的帖子并理解了,但是我无法理解以下代码的 cmets。此外,没有人在构造函数中提到函数的函数参数中的 this 关键字。尤其是第二句粗体字,让我一头雾水:

我们需要将this的引用存储到self,这样我们就可以 在 setTimeout(或任何回调)函数中使用当前上下文。 在 setTimeout 函数中使用this 将引用这些函数, 不是 Radio 类

引用自:http://www.hacksparrow.com/node-js-eventemitter-tutorial.html

【问题讨论】:

  • “this 的值在函数中使用时,是“拥有”该函数的对象。” - 不。 value of this 取决于函数的调用方式。
  • 错了吗?我是从w3schools.com/js/js_function_invocation.asp 引用的。
  • @metis 是的,这是不正确的(或者他们对“拥有”的使用具有误导性)。现在您知道 w3school 是多么糟糕的学习资源了。
  • 这并不完全准确。更好的是:"this 在传递给setTimeout 的回调函数中将代表window 对象,因为一旦发生超时,浏览器将调用该回调。"
  • @metis,如果你写了this.emit('close', station);,你会得到一个运行时错误,说this.emit不是一个函数。这是因为当时thiswindow(如上所述)。

标签: javascript node.js this


【解决方案1】:

this 关键字的值将根据当前上下文更改值。 this 工作原理的完整描述有些复杂。有关详细信息,请参阅MDN

在您的情况下,当最终调用 setTimeout 调用中的匿名函数时,this 将具有不同的值。但是,self 变量仍然可用。

【讨论】:

    【解决方案2】:

    函数中“this”的目的是引用调用该函数的对象。由于您使用 setTimeout 将匿名函数传递给窗口,因此该函数中的任何“this”调用都将引用窗口对象。

    您可以使用 Javascript 绑定函数在回调函数中保留“this”的上下文,而不管它在哪里被调用。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    您的 setTimeout 函数如下所示:

    setTimeout(function() {
        this.emit('close', station);
    }.bind(this), 5000);
    

    【讨论】:

    • “函数中'this'的目的是引用调用该函数的对象” - 更准确的说法是this指的是函数应该操作的对象(假设函数的目的与对象完全相关),并且可以根据调用函数的方式将其设置为 any 对象。跨度>
    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2013-12-17
    相关资源
    最近更新 更多