如果您修复constructor
属性以指向正确的功能(即B
)
B.prototype.constructor = B;
然后您可以通过以下方式访问构造函数的名称
this.parentMethod = function() {
alert(this.constructor.name);
}
请注意,这Function.name
是一个非标准属性,可能不适用于所有浏览器。另一种方法是通过覆盖parentMethod
或添加属性到具有函数名称的实例来硬编码函数名称。您也可以直接使用函数引用 ( this.constructor
),具体取决于您要实现的目标。
设置继承的更好方法是使用Object.create
[MDN]并在子构造函数中调用父构造函数:
function A() {}
A.prototype.parentMethod = function() {};
function B() {
A.call(this); // call parent constructor
}
B.prototype = Object.create(A.prototype); // establish inheritance
B.prototype.constructor = B;