obj.prototype.__proto__ = events.EventEmitter.prototype
我有时看过上面的代码,我在谷歌上搜索了一下,他们说这一行将所有 EventEmitter 属性复制到 obj. 而且我还看到这样的代码:
obj.__proto__ = events.EventEmitter.prototype
所以我想知道它们是否相同?
在这篇文章中看到了第一个用法,作者给出了例子:
var events = require('events');
function Door(colour) {
this.colour = colour;
events.EventEmitter.call(this);
this.open = function()
{
this.emit('open');
}
}
Door.prototype.__proto__ = events.EventEmitter.prototype;
var frontDoor = new Door('brown');
frontDoor.on('open', function() {
console.log('ring ring ring');
});
frontDoor.open();
他解释说:
此行:
Door.prototype.__proto__ = events.EventEmitter.prototype;
将所有 EventEmitter 属性复制到 Door 对象。
至于第二种方式,我是在 hexo 的源码中看到的,在 init.js 中有代码:
var hexo = global.hexo = {
get base_dir(){return baseDir},
get public_dir(){return baseDir + 'public/'},
get source_dir(){return baseDir + 'source/'},
get theme_dir(){return baseDir + 'themes/' + config.theme + '/'},
get plugin_dir(){return baseDir + 'node_modules/'},
get script_dir(){return baseDir + 'scripts/'},
get scaffold_dir(){return baseDir + 'scaffolds/'},
get core_dir(){return path.dirname(dirname) + '/'},
get lib_dir(){return dirname + '/'},
get version(){return version},
get env(){return env},
get safe(){return safe},
get debug(){return debug},
get config(){return config},
get extend(){return extend},
get render(){return render},
get util(){return util},
get call(){return call},
get i18n(){return i18n.i18n},
get route(){return route},
get db(){return db}
};
hexo.cache = {};
// Inherits EventEmitter
hexo.__proto__ = EventEmitter.prototype;
// Emit "exit" event when process about to exit
process.on('exit', function(){
hexo.emit('exit');
});