简体   繁体   English

在多级继承中查找构造函数

[英]Finding the constructor in multi-level inheritance

I want to find out the specific constructor used to instantiate the object in javascript, not the one which is last in the prototype chain. 我想找出用于实例化javascript中对象的特定构造函数,而不是原型链中最后一个的构造函数。 Consider the code : 考虑代码:

function F(){};
function E(){};
function D(){};
function C(){};
function B(){};
function A(){};

E.prototype= new F();
D.prototype= new E();
C.prototype= new D();
B.prototype= new C();
A.prototype= new B();

a=new A();

Find fiddle here 在这里找到小提琴

a.constructor returns function F(){} , but I want a method that returns function A(){} , since A is the constructor used to instantiate the object. a.constructor返回function F(){} ,但是我想要一个返回function A(){} ,因为A是用于实例化对象的构造函数。

How can that be achieved ? 如何实现?

With the way you inherit from parent it's not possible to access original constructor, because when you write 从父类继承的方式无法访问原始构造函数,因为在编写时

A.prototype = new B();

A.prototype.constructor indeed points to B not A anymore. A.prototype.constructor确实指向B而不是A

With this pattern for prototypical inheritance you have to manually set constructor properly. 使用这种原型继承模式,您必须手动正确设置构造函数。 So you either do it for each extended class manually or you can use helper function: 因此,您可以手动为每个扩展类执行此操作,也可以使用辅助函数:

 function inherit(C, P) { C.prototype = new P(); C.prototype.constructor = C; } function F(){}; function E(){}; function D(){}; function C(){}; function B(){}; function A(){}; inherit(E, F); inherit(D, E); inherit(C, D); inherit(B, C); inherit(A, B); var a = new A(); var c = new C() document.write( a.constructor + "<br>" ); document.write( c.constructor ); 

Do the following: 请执行下列操作:

function F(){};
function E(){};
function D(){};
function C(){};
function B(){};
function A(){};

E.prototype= new F();
E.prototype.constructor = E;
D.prototype= new E();
D.prototype.constructor = D;
C.prototype= new D();
C.prototype.constructor = C;
B.prototype= new C();
B.prototype.constructor = B;
A.prototype= new B();
A.prototype.constructor = A;

Did you check John Resig's Class.js ? 您是否检查过John Resig的Class.js? http://ejohn.org/blog/simple-javascript-inheritance/ It implements inheritance in javascript, and makes possible what you're asking for. http://ejohn.org/blog/simple-javascript-inheritance/它实现了javascript中的继承,并使得您所要求的成为可能。

Edit: Sorry. 编辑:对不起。 I was wrong. 我错了。 However, you can add something like this to your declarations : 但是,您可以在声明中添加以下内容:

A.prototype= new B();
A.prototype.constructor = B; 

Not sure of all the consequences it can have, but it seems to work! 不确定它可能带来的所有后果,但它似乎有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM