在下面的示例中是否可以获取派生“类”的名称?我想以某种方式让输出为“ChildClass”,但它是“ParentClass”。
function ParentClass() { this.name = 'Bob' }
function ChildClass() { this.name = 'Fred' }
ChildClass.prototype = Object.create(ParentClass.prototype);
var child_instance = new ChildClass()
console.log('ChildClass type:', child_instance.constructor.name)
我意识到我能做到this.my_type = 'ChildClass'
在 ChildClass 构造函数中,但我有许多扩展 ParentClass 的类,并且在任何地方执行此操作会很不方便。
您的情况的问题是您正在覆盖prototype
的财产ChildClass
但你没有重置constructor
新原型上的属性。您需要添加一行:
function ParentClass() {
this.name = "Bob";
}
function ChildClass() {
this.name = "Fred";
}
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass; // add this line to your code
现在您的代码将按预期工作。以下答案解释了为什么您的原始代码不起作用:https://stackoverflow.com/a/8096017/783743 https://stackoverflow.com/a/8096017/783743
就我个人而言,我不喜欢像这样编写“类”,其中构造函数和原型分别悬空。打字太乏味、语无伦次、眼睛疼痛并且难以维护。因此,我使用以下实用函数来创建类:
function defclass(base, body) {
var uber = base.prototype;
var prototype = Object.create(uber);
var constructor = (body.call(prototype, uber), prototype.constructor);
constructor.prototype = prototype;
return constructor;
}
现在您可以按如下方式创建类:
var ParentClass = defclass(Object, function () {
this.constructor = function () {
this.name = "Bob";
};
});
var ChildClass = defclass(ParentClass, function () {
this.constructor = function () {
this.name = "Fred";
};
});
这种方法有几个优点:
- 继承和类定义已合二为一。
- 构造函数只是另一个原型方法。
- 一切都很好地封装在一个闭包中。
- 调用基类原型方法很容易。
- 您可以轻松创建私有静态函数。
希望有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)