【问题标题】:Iterate Constructor Chain Up迭代构造函数链上
【发布时间】:2014-11-10 13:43:20
【问题描述】:

假设我有这样的事情:

function A() {}

function B() {}
B.prototype = Object.create(A.prototype);

function C() {}
C.prototype = Object.create(B.prototype);

var inst = new C();

我现在可以执行 inst instanceof C == true、inst instanceof B == true、instanceof C == true。

但是我如何从 C() 的实例开始“迭代”构造函数,以便它返回函数 C()、函数 B()、函数 A(),然后我可以用它们来实例化另一个实例。

【问题讨论】:

  • 迭代函数是什么意思?

标签: javascript


【解决方案1】:

您可以通过以下方式迭代原型

for (var o=inst; o!=null; o=Object.getPrototypeOf(o))
    console.log(o);
// {}
// C.prototype
// B.prototype
// A.prototype
// Object.prototype

但是,这只会迭代原型链。没有“构造函数链”这样的东西。如果你想访问构造函数,你需要在继承时在原型上适当地set the .constructor property

function A() {}

function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

function C() {}
C.prototype = Object.create(B.prototype);
C.prototype.constructor = C;

var inst = new C();

for (var c=inst.constructor; c!=null; (c=Object.getPrototypeOf(c.prototype)) && (c=c.constructor))
    console.log(c);
// C
// B
// A
// Object

然后我可以用它来实例化另一个实例

为此,您只需要知道C,而不是“链”。如果您正确设置了C.prototype.constructor,则可以通过inst.constructor 访问它。

但是,从任意构造函数实例化对象可能是个坏主意;您不知道所需的参数。我不知道你actually want to do 是什么,但你的请求可能暗示了设计缺陷。

【讨论】:

    【解决方案2】:

    使用对象原型的构造函数属性向上链。

    例如,在你的代码之后:

     C.prototype.constructor === A
    

    是真的,是的

      inst.constructor.prototype.constructor === A
    

    ...等等。

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多