可能重复:
JavaScript“this”关键字
我对EventEmitter
node.js 中用于 's的回调有点困惑。
var events = require("events");
function myObject() {
this.name = "Test Object";
this.x = 99;
this.y = 100;
}
myObject.prototype = new events.EventEmitter();
var myobject = new myObject();
myobject.addListener('dbg1', function() {
console.log("this.name = " + this.name); //this.name gives the name not undefined
console.log("myobject.name = " + myobject.name); //so does this
});
myobject.emit('dbg1');
为什么this
里面的回调指的是 myobject
?回调函数的闭包是这段代码中的全局范围,对吗?