【发布时间】:2023-03-22 06:03:01
【问题描述】:
这是我的问题: 假设我有一个带有原型 X 的构造函数 A(); 现在我有另一个构造函数 B,我想从 A 继承。 所以我必须这样做:B.prototype = Object.create(A.prototype);
但是为什么我不能调用 B.prototype = A.prototype ,因为 Object.create(A.prototype) 它等于 A.prototype?
或者我可以使用这样的函数来代替调用 Object.create:
function inherit(p) {
function f(){};
f.prototype = p;
return new f();
}
然后是B.prototype = inherit(A.prototype)。
有什么区别? 为什么不能调用 B.prototype = A.prototype?
【问题讨论】:
-
因为继承需要将原型指向构造函数。
标签: javascript oop inheritance prototype