从标准 setPrototypeOf函数的MDN文档 以及非标准属性: __proto__
强烈建议不要改变对象的[[Prototype]],无论如何实现,因为它非常慢并且不可避免地减慢了现代JavaScript实现中后续执行的速度.
使用Function.prototype添加属性是在添加成员函数JavaScript类的方式.然后如下所示:
function Foo(){}
function bar(){}
var foo = new Foo();
// This is bad:
//foo.__proto__.bar = bar;
// But this is okay
Foo.prototype.bar = bar;
// Both cause this to be true:
console.log(foo.__proto__.bar == bar); // true
Run Code Online (Sandbox Code Playgroud)
为什么foo.__proto__.bar = bar;不好?如果它的坏不是Foo.prototype.bar = bar;那么糟糕?
那么为什么会出现这样的警告:它非常缓慢并且不可避免地减慢了现代JavaScript实现中后续执行的速度.当然Foo.prototype.bar = bar;不是那么糟糕.
更新也许通过突变他们意味着重新分配.见接受的答案.
我一直在玩EventEmitter,但我对如何从模块中实现它感到困惑.我见过几种不同的方式,它们似乎都有效.以下是我见过的一些内容:
从这里:
var Twitter = function() {...};
Twitter.prototype = new events.EventEmitter;
Run Code Online (Sandbox Code Playgroud)
但是在"掌握节点"中他们这样做:
function Dog(name) {
this.name = name;
EventEmitter.call(this);
}
Dog.prototype.__proto__ = EventEmitter.prototype;
Run Code Online (Sandbox Code Playgroud)
(为什么你需要.call它?)
然后在我自己的代码中我尝试了另一种方式:
function Class() {}
Class.prototype = EventEmitter.prototype;
Run Code Online (Sandbox Code Playgroud)
它们都是以自己的方式继承EventEmitter,所以最简单的解决方案不是最好的吗?