javascript - 对象函数中的 this 关键字

标签 javascript node.js this

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

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

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;

我阅读了类似的帖子并理解了,但是我无法理解下面代码的注释。此外,没有人提到构造函数内函数的函数参数中的 this 关键字。尤其是第二句话,写得粗体,让我完全困惑:

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

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

最佳答案

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

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

关于javascript - 对象函数中的 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902006/

相关文章:

javascript - Vue.js 总是从数组中删除最后一项

javascript - 在 Javascript 中缓存和预取过期的 promise

javascript - 如何在 Sails.js 中进行严格关联

node.js - 无法从本地托管的 Node.js 应用程序连接到 AWS DB

javascript - JavaScript 如何确定何时为函数调用提供 "this"上下文?

jQuery 仅在悬停时向此嵌套元素添加类

javascript - 如何使用 extjs 4 制作只读复选框

javascript - 如何在 jquery POST 中将 enctype 作为 multipart/form-data 发送

javascript - 仅允许在经过设定的时间后调用函数

javascript - 如何在 JavaScript 上访问 "this"的父级?