【发布时间】: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不是一个函数。这是因为当时this是window(如上所述)。
标签: javascript node.js this