如果修复constructor
属性指向正确的功能(即B
)
B.prototype.constructor = B;
然后你就可以通过
this.parentMethod = function() {
alert(this.constructor.name);
}
注访问的构造函数的名字虽然即Function.name
is a non-standard property,并可能无法在所有浏览器中运行。替代方法是通过覆盖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;
功能没有名称。函数声明创建一个引用创建的函数对象的变量。任何数量的变量都可以引用同一个函数对象,有些变量可以根本没有引用('name')。那叫什么名字? – RobG 2013-04-25 12:31:21
你想得到什么? B没有任何方法。父母如何知道孩子的任何事情? – 2013-04-25 12:31:51