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

标签 javascript prototype

我有以下继承代码:

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/

相关文章:

javascript - 如何使用 javascript 或 jQuery 重新排列 html 元素的显示顺序?

javascript - 如何确定数据表中的行是否可见

javascript - 函数未分配给 Chrome 中另一个函数的原型(prototype)

javascript - 使用 proto 创建一个 Storage 子类

JavaScript 将字符串和整数从 PHP 传递到函数中

javascript - Svg 缩放到特定的矩形

javascript - 在 iFrame 中设置 cookie

javascript - 我将如何在纯 JavaScript 中暂时禁用该事件?

javascript - 修改JavaScript内置原型(prototype)是不是反模式?

javascript - 如果修改构造函数的原型(prototype)对象,现有构造函数是否不受影响?