0
最近我写了一个es6类的小型库。现在我决定将它重写为es5代码。因为文库使用类继承很多(类A延伸B),我不得不写一小块的代码来模拟ES6类继承:JS Getters/Setter原型继承
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
}
但我了解到,这个代码是不是能够在干将相结合的基础功能/定义这样的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方法在功能定义亲输入?
“*现在我已经决定重写它ES5代码* “ - 为什么?让一个transpiler为你做这份工作。 – Bergi
“*'B.prototype.isLoading(){ return this._loading; }'*”是一个语法错误。如果没有,请将您的Internet Explorer移开。 – Bergi
是的,谢谢你,只是在例子中的一个错误,这个代码我实际上并没有使用 –