[英]Javascript inheritance of properties defined with Object.defineProperty
我有以下父类......
function Parent(id, name, parameters) { Object.defineProperty(this, "id", { value: id }); Object.defineProperty(this, "name", { value: name, writable: true }); };
和相应的子类:
function Child(id, name, parameters) { Object.defineProperty(this, "phone", { value: parameters.phone, writable: true }); };
我尝试通过添加类似Child.prototype = Object.create(Parent.prototype)的东西来应用继承; ,但这显然不起作用。
我如何从Parent类继承,以便我可以使用属性id和name。
我尝试通过添加类似
Child.prototype = Object.create(Parent.prototype);
东西来应用继承Child.prototype = Object.create(Parent.prototype);
是的,你应该这样做,在.prototype
对象之间创建一个原型链。 你有自己定义的方法,不是吗?
我如何从Parent类继承,以便我可以使用属性id和name。
您基本上需要对Parent
构造函数进行“超级”调用,以便它在Child
实例上设置您的属性:
function Child(id, name, parameters) {
Parent.call(this, id, name, parameters);
Object.defineProperty(this, "phone", {
value: parameters.phone,
writable: true
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.