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
是的,謝謝你,只是在例子中的一個錯誤,這個代碼我實際上並沒有使用 –