如果您跳到 this question 中的第一个答案你会看到他使用了 Employee.prototype = new Person();
继承Person.prototype
至Employee.prototype
,但是当我从 Udacity 学习 JavaScript OOP 类(class)时,他们使用了 Employee.prototype = Object.create(Person.prototype);
反而。
正确的是什么:
Employee.prototype = new Person();
或
Employee.prototype = Object.create(Person.prototype);
或
Employee.prototype = Person.prototype;
如果这个问题重复,请给我推荐一些好的答案。
最佳答案
Employee.prototype = Object.create(Person.prototype);
是最干净的。
使用 Employee.prototype = new Person();
,您会发现对 Person
中的 this
的赋值会影响您的所有 Employee
实例。也许你不想要这样。也可能有其他副作用。
例如(使用一些 ES2015 语法):
function Person(name = "fred") {
this.name = name;
}
function Employee(...args) {
Person.call(this, ...args);
}
Employee.prototype = new Person();
var e1 = new Employee();
console.log(e1.name); // fred
您需要阅读 Person
代码才能了解为什么默认情况下所有员工都被称为 fred
。在本例中这是微不足道的,但在现实世界中,许多函数都很长且有状态,并且很容易被误读。
想象一下,如果Person
依赖于某些外部状态。 Employee.prototype
的值可能会根据其他代码是否已执行而发生变化。您不希望原型(prototype)链中出现这种不确定性。
例如:
let personCount = 0;
function Person() {
this.id = personCount ++;
}
// ...
Employee.prototype = new Person();
// what `id` do Employees inherit? we don't know!
// it depend on how many times `Person` has been called,
// and by creating `Employee.prototype` we changed the state even further. Uhoh.
Object.create(Person.prototype)
更容易推理,因为没有用户函数调用;没有逻辑。您只需检查静态 Person.prototype
即可查看您继承的内容。
原型(prototype)仍然有可能具有可变值,因此存在一些不确定性,但是创建对象的行为本身没有副作用,因此这种错误的可能性较小。
使用 Employee.prototype = Person.prototype;
,对 Employee.prototype
的更改将影响所有 Person
实例。您可能不希望这样。
关于javascript - 如何正确委托(delegate)类原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164778/