我有以下继承代码:
SubClass= function () {
ParentClass.call(this);
}
SubClass.prototype = Object.create(ParentClass.prototype);
SubClass.prototype.constructor = SubClass;
但是,我也想在子类中定义一些属性:
SubClass.prototype = {
get x() {
return this.newX;
},
set x(val) {
this.newX = val;
alert("X has a value of " + this.newX);
}
}
我遇到的问题是将两者结合起来。换句话说,在第一个代码示例中我要说的是:
SubClass.prototype = Object.create(ParentClass.prototype);
但是在第二个代码示例中我要说的是:
SubClass.prototype = {...
我怎样才能同时实现这两个目标?允许我从父类继承并使用相同原型(prototype)定义定义属性的语法是什么?
谢谢:)
最佳答案
通过将属性描述符传递给 Object.defineProperty
来定义属性:
Object.defineProperty(SubClass.prototype, 'x', {
configurable: true,
get: function () {
return this.newX;
},
set: function (val) {
this.newX = val;
alert("X has a value of " + this.newX);
},
});
也可以将包含属性描述符的对象传递给Object.create
:
function SubClass() {
ParentClass.call(this);
}
SubClass.prototype = Object.create(ParentClass.prototype, {
constructor: {
configurable: true,
writable: true,
value: SubClass,
},
x: {
configurable: true,
get: function () {
return this.newX;
},
set: function (val) {
this.newX = val;
alert("X has a value of " + this.newX);
},
}
});
如果您可以使用 ES6 类,那就更好了:
class SubClass extends ParentClass {
get x() {
return this.newX;
}
set x(val) {
this.newX = val;
alert("X has a value of " + this.newX);
}
}
您还可以制作这种有用的功能:
function extend(target, source) {
Object.getOwnPropertyNames(source).forEach(function (name) {
var descriptor = Object.getOwnPropertyDescriptor(source, name);
Object.defineProperty(target, name, descriptor);
});
}
并像这样使用它:
extend(SubClass.prototype, {
get x() {
return this.newX;
},
set x(val) {
this.newX = val;
alert("X has a value of " + this.newX);
},
});
关于javascript - 如何在子类中定义 getter 和 setter 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43535357/