Al *_* R. 9 javascript ecmascript-6
所以我一直在了解 JavaScript 的一些新特性,并且一直在阅读 Object.setPrototypeOf()。我从MDN 中遇到了这段代码,它处理从常规对象的继承。但我对他们在这里如何使用 Object.setPrototypeOf() 感到困惑。我希望他们写
Object.setPrototypeOf(Dog, Animal)
Run Code Online (Sandbox Code Playgroud)
与下面的操作相反。他们为什么这样写?
var Animal = {
speak() {
console.log(this.name + ' makes a noise.');
}
};
class Dog {
constructor(name) {
this.name = name;
}
}
Object.setPrototypeOf(Dog.prototype, Animal);// If you do not do this you will get a TypeError when you invoke speak
var d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
Run Code Online (Sandbox Code Playgroud)
调用的原因Object.setPrototypeOf
是为了确保Dog
构造函数创建的任何对象都将Animal
在其原型链中获取该对象。设置构造函数本身的原型是错误的(不要与构造函数的prototype
属性混淆,这确实是用词不当),因为构造函数在d
的原型链中没有位置。
创建的Dog
对象不会进入Dog
其原型链,而是Dog.prototype
. Dog
是仅仅由对象创建的车辆,它不应该自己成为原型链的一部分。
您可以改为在Dog
构造函数中执行此操作:
Object.setPrototypeOf(this, Animal)
Run Code Online (Sandbox Code Playgroud)
这使得原型链的长度缩短了一步,但缺点是现在d instanceof Dog
将不再如此。它只会是一个Animal
. 这是一个坑,它解释了为什么保留原始Dog.prototype
对象是好的,同时设置其原型为Animal
,因此现在d
既是 aDog
又是 an Animal
。
归档时间: |
|
查看次数: |
10171 次 |
最近记录: |