【问题标题】:javascript constructor.prototype inheriting another constructor.prototype [duplicate]javascript constructor.prototype继承另一个constructor.prototype [重复]
【发布时间】: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


【解决方案1】:

这是因为如果你添加一些东西到 B.prototype 你也会添加到 A.prototype

但是为什么我不能调用 B.prototype = A.prototype Object.create(A.prototype) 是否等于 A.prototype?

如果您使用B.prototype = A.prototype,那么两个原型将指向同一个引用。如果您执行B.prototype = Object.create(A.prototype),那么B.prototype 将只取A.prototype 中的值,引用将不一样。

所以,

B.prototype = A.prototype
B.prototype === A.prototype
// OUTPUT: true;

B.prototype = Object.create(A.prototype)
B.prototype === A.prototype
// OUTPUT: false;

编辑

您可以使用generated typescript code example 扩展而不使用Object.create

// b -> base class
// d -> new class
var __extends = function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

【讨论】:

  • 类似于 B.protoype.x = function(){} ?
  • 是的,它也会导致 A.prototype.x = function(){}。 Object.create 将返回一个新的对象。
  • 所以,总而言之,这一切都与参考有关……对吧?
  • 我可以使用类似:B.prototype = A.prototype; B.prototype = new B();'for(prop in A.prototype) { B.prototype[prop] = A.prototype[prop]; } 吗?
  • 简短的回答是否定的。如果你这样做,new B() instanceof A 将返回 false。您可以查看我的编辑以获取没有Object.create 的完整解决方案
【解决方案2】:

因为继承需要将原型指向构造函数。 所以你可以做任何一个。

B.prototype = Object.create(A.prototype)

或者

B.prototype = new A();

【讨论】:

  • 我知道我可以做到,我的问题是为什么不更简单...比如 B.prototype = A.prototype 因为按顺序 Object.create(A.prototype) 将返回相同的像 A.prototype 这样的对象
  • 正如我已经提到的 Javascript 继承的工作方式。 Object 本身用作继承的模板。同样正如@wedney 所解释的那样,您所做的只是指向相同的引用而不是实现继承。
  • 是的,但是对引用进行抽象,分配原型没有区别……很奇怪。
  • 看看这个 B.prototype = A.prototype; B.prototype = new B();现在我可以在不使用 Object.create 的情况下从 A 继承,对吧?
  • 不,您不应该使用new A()(或new B())来创建原型。见herethere
猜你喜欢
  • 2015-04-18
  • 2016-10-29
  • 2010-10-13
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多