1

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

结合.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?

4

1 回答 1

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;

}
于 2017-07-17T20:08:27.087 回答