给定两个类,我想将其中一个的方法提供给另一个:
class a {}
class b {say() {console.log('hello')}}
var foo = new a();
这是如何工作的:
a.prototype.say = b.prototype.say;
foo.say(); //'hello'
但这不是吗?
a.prototype = b.prototype;
foo.say(); //foo.say is not a function
明确地说,我不是在问如何将一个类的方法提供给另一个类,而是在问为什么原型(prototype)会这样。
奖励问题:在类 block 中定义方法与通过直接将其分配给原型(prototype)来定义它有什么区别?
最佳答案
原因是类上的 prototype
是不可写、不可配置的属性:
class a {}
class b {say() {console.log('hello')}}
console.log(Object.getOwnPropertyDescriptor(a,'prototype'))
不可写意味着你不能重新分配属性 prototype
不可配置意味着你不能改变属性使 writable: true
或删除属性.
结果是这个没有效果:
class a {}
class b {say() {console.log('hello')}}
a.prototype = b.prototype;
console.log(a.prototype === b.prototype)
但是不可写只意味着你不能改变与属性 a.prototype
相关联的值——它总是指向同一个对象——这并不意味着你不能向该对象添加属性。这就是为什么您仍然可以添加 a.prototype.say
的原因。
关于javascript - 为什么我不能用另一个类的原型(prototype)替换一个类的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51993372/