我不明白下面代码中的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
toself
, so that we can use the current context in the setTimeout (or any callback) functions. usingthis
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/