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

Finding the constructor in multi-level inheritance

我想找出用于在 javascript 中实例化对象的特定构造函数,而不是原型链中最后一个。考虑代码:

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();

查找fiddlehere

a.constructorreturnsfunction F(){},但是我想要一个returnsfunction A(){}的方法,因为A是用来实例化的构造函数对象。

如何实现?

你检查过 John Resig 的 Class.js 了吗? http://ejohn.org/blog/simple-javascript-inheritance/ 它在 javascript 中实现继承,并使您的要求成为可能。

编辑: 对不起。我错了。但是,您可以在声明中添加类似这样的内容:

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

不确定它可能产生的所有后果,但它似乎有效!

执行以下操作:

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;

通过从父级继承的方式,无法访问原始构造函数,因为当您编写

A.prototype = new B();

A.prototype.constructor 确实指向 B 而不是 A

使用这种原型继承模式,您必须手动正确设置构造函数。所以你要么手动为每个扩展 class 做,要么你可以使用辅助函数:

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 );