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

时间:2017-04-21 06:24:15

标签: javascript prototype

我有以下继承代码:

echo json_encode(array("package_name"=>$package_name,"package_type"=>$package_type,"discount"=>$discount,"amnt_discount"=>$amnt_discount,"tax"=>$tax,"amnt_tax"=>$amnt_tax,"count"=>$count,"job_post"=>$job_post,"package_price"=>$package_price,"valitity"=>$valitity));

但是,我想在子类中定义一些属性:

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

我怎样才能实现这两个目标?什么是允许我从父类继承并使用相同的原型定义定义属性的语法?

谢谢:)

1 个答案:

答案 0 :(得分:1)

通过将属性描述符传递给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类,那么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);
    },
});