最近我在 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?