2

函数 B 扩展 A,当我调用 B 子函数parentMethod()对象的对象时,如何在父函数 A 中获取 B 函数名称。

function A() {

    this.parentMethod = function() {
         //alert('display B function name');
    }
}

function B() {


}


B.prototype = new A();

var b = new B();  
b.parentMethod();
4

2 回答 2

2

最简单的方法是:

function A() {

    this.parentMethod = function() {
         alert(this.constructor.name);
    }
}

function B() {

}


B.prototype = new A();  
B.prototype.constructor = B; //Add this line.

var b = new B();  
b.parentMethod();

现在,当您调用 parentMethod 时,它会将 B 显示为构造函数名称。

于 2013-04-25T15:13:19.780 回答
0

如果您修复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;
于 2013-04-25T12:32:25.880 回答