Javascript 如何在子类中定义getter和setter属性

Javascript 如何在子类中定义getter和setter属性,javascript,prototype,Javascript,Prototype,我有以下继承代码: SubClass= function () { ParentClass.call(this); } SubClass.prototype = Object.create(ParentClass.prototype); SubClass.prototype.constructor = SubClass; 但是,我也想在子类中定义一些属性: SubClass.prototype = { get x() { return this.newX;

我有以下继承代码:

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 = {...
但在第二个代码示例中,我要说:

SubClass.prototype = Object.create(ParentClass.prototype);
SubClass.prototype = {...
我怎样才能做到两者?允许我从父类继承并使用相同的原型定义定义属性的语法是什么


谢谢:)

通过向
对象传递属性描述符来定义属性。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);
    },
});
还可以将包含属性描述符的对象传递给
对象。创建

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);
    },
});