关于原型继承的JS Getters / Setters

时间:2017-07-16 22:43:11

标签: javascript oop inheritance javascript-inheritance

最近我在es6课程中编写了一个小型库。现在我决定将其重写为es5代码。因为库很多都使用了类继承(类A扩展了B),所以我不得不编写一小段代码来模拟es6类的继承:

combine.js

module.exports = function () {
    var _arguments = arguments;

    var Class = function () {
        for (var i = 0; i < _arguments.length; i++) {
            if (typeof _arguments[i] === 'function') {
                _arguments[i].call(this);
            }
        }
    }

    var prototype = { };
    for (var i = 0; i < _arguments.length; i++) {
        if (typeof _arguments[i] === 'function') {
            prototype = Object.assign(prototype, _arguments[i].prototype);
        }
    }
    Class.prototype = prototype;

    return Class
}

但是据我所知,这段代码无法组合在基本函数上定义的getter / setter:

var combine = require('./combine.js');

function A() {
    this._loading = false;
}

Object.defineProperty(A.prototype, 'loading', {
    get() {
        return this._loading;
    },
    set(value) {
        this._loading = value;
    }
});

function B() { }

B.prototype.isLoading = function () {
    return this._loading;
}

B.prototype.setLoading = function (loading) {
    this._loading = loading;
}

var C = combine(A, B);
var c = new C();

console.log(c.isLoading()); // false
console.log(c.loading); // c.loading is undefined

c.setLoading(true);
console.log(c.isLoading()); // true
console.log(c.loading); // c.loading is undefined

c.loading = false;
console.log(c.isLoading()); // true
console.log(c.loading); // false

有没有办法继承在函数原型上定义的getter / setter?

1 个答案:

答案 0 :(得分:0)

最后,感谢@ Bergi的链接,我来了mixin函数的原型,看起来像这样:

module.exports = function () {

    var _arguments = arguments;

    var Class = function () {
        for (var i = 0; i < _arguments.length; i++) {
            if (typeof _arguments[i] === 'function') {
                _arguments[i].call(this);
            }
        }
    }

    var prototype = { }
    for (var x = 0; x < _arguments.length; x++) {
        if (typeof _arguments[x] === 'function') {
            var properties = Object.getOwnPropertyNames(_arguments[x].prototype);
            for (let y in properties) {
                if (properties[y] != 'constructor') {
                    Object.defineProperty(
                        prototype,
                        properties[y],
                        Object.getOwnPropertyDescriptor(_arguments[x].prototype, properties[y])
                    );
                }
            }
        }
    }
    Class.prototype = prototype;

    return Class;

}