gpt4 book ai didi

javascript - 原型(prototype)继承上的 JS Getters/Setters

转载 作者:行者123 更新时间:2023-11-28 04:25:02 25 4
gpt4 key购买 nike

最近我用 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

有没有办法继承函数原型(prototype)上定义的 getters/setters?

最佳答案

最后,感谢 @Bergi 的链接,我得到了 mixin 函数的工作原型(prototype),如下所示:

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;

}

关于javascript - 原型(prototype)继承上的 JS Getters/Setters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45133921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com