[英]ES6 Class extends Array: workaround for ES5 Babel transpile
I have some ES6 class inherited from Array
: 我有一些继承自Array
ES6类:
class Cache extends Array {
add(item) {
if(!item.doNotRemove)
this.push(item)
}
printLast() {
if(this.length > 0)
console.log(this[this.length - 1].text)
}
}
The following code works fine 以下代码工作正常
const myCache = new Cache()
myCache.add({text: 'hello'})
myCache.add({text: 'world'})
myCache.add({text: '!!!', doNotRemove: true})
myCache.printLast() // world
But I can't transpile it to ES5 with Babel (I know there is an issue ), and currently as a workaround I apply the following approach: 但我无法通过Babel将其转发给ES5(我知道存在问题 ),目前作为一种解决方法,我采用以下方法:
const CacheProto = {
add(item) {
if(!item.doNotRemove)
this.push(item)
},
printLast() {
if(this.length > 0)
console.log(this[this.length - 1].text)
}
}
function Cache() {
return Object.assign(Object.create(Array.prototype), CacheProto)
}
This satisfies the code above ( myCache = new Cache()
etc). 这满足上面的代码( myCache = new Cache()
等)。 But as you can see, it's just an Array instance extending. 但正如您所看到的,它只是一个扩展的Array实例。
The question 这个问题
Is it possible to have a workaround with original class ? 是否有可能与原始类有一个解决方法? Of course, without extends Array
. 当然,没有extends Array
。 Is it possible to have add
and printLast
methods and all Array.prototype
methods on the prototype chain, not on instance? 是否可以在原型链上add
和printLast
方法以及所有Array.prototype
方法,而不是实例?
I have made a little plunker for possible research. 我做了一个小plunker可能的研究。
You only really have to extend Array
if you want to the magic .length
-affecting property assignment ( arr[42] = 21;
) behavior or most of the array methods. 如果你想要魔术.length
-affecting属性赋值( arr[42] = 21;
)行为或大多数数组方法,你只需要扩展Array
。 If you don't need that, using an array as internal data structure seems to be the simplest (and most compatible) solution: 如果您不需要,使用数组作为内部数据结构似乎是最简单(和最兼容)的解决方案:
class Cache {
constructor() {
this._data = [];
}
add(item) {
if(!item.doNotRemove)
this._data.push(item)
}
printLast() {
if(this.length > 0)
console.log(this._data[this._data.length - 1].text)
}
}
You can easily expose .length
and other methods. 您可以轻松地公开.length
和其他方法。
An easy way to pull in multiple methods from Array.prototype
would be: 从Array.prototype
提取多个方法的简单方法是:
['reduce', 'filter', 'find', ...].forEach(method => {
Cache.prototype[method] = function(...args) {
return this._data[method](...args);
};
});
// Or if you want them to be non-enumerable
// (like they would if they were defined via `class` syntax)
Object.defineProperties(
Cache.prototype,
['reduce', 'filter', 'find', ...].reduce((obj, method) => {
obj[method] = {
value: function(...args) { return this._data[method](...args); },
enumerable: false,
configurable: true,
writeable: true,
};
return obj;
}, {})
);
You can manipulate the prototype directly using __proto__
, it's also now kind of been standardised for backward compatibility reasons so should be safe to use. 您可以使用__proto__
直接操作原型,它现在也因为向后兼容性而被标准化,因此应该可以安全使用。
More info here -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto 更多信息 - > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
edit: Like @Bergi pointed out, using a shim with Object.setPrototypeOf
would future proof this technique too. 编辑:像@Bergi指出的那样,使用带有Object.setPrototypeOf
的垫片也将证明这种技术的未来。
function Cache() { var arr = []; arr.push.apply(arr, arguments); arr.__proto__ = Cache.prototype; //if using a shim, (better option). //Object.setPrototypeOf(arr, Cache.prototype); return arr; } Cache.prototype = new Array; Cache.prototype.printLast = function () { if(this.length > 0) console.log(this[this.length - 1].text) } Cache.prototype.add = function (item) { if(!item.doNotRemove) this.push(item) } const myCache = new Cache() myCache.add({text: 'hello'}) myCache.add({text: 'world'}) myCache.add({text: '!!!', doNotRemove: true}) myCache.printLast() // world myCache.forEach(function (item) { console.log(item); }); console.log("is Array = " + Array.isArray(myCache));
This is a little hacky, but I'm pretty sure it does what you are looking for. 这有点hacky,但我很确定它能满足您的需求。
function Cache() {} Cache.prototype = new Array; Cache.prototype.add = function(item) { if (!item.doNotRemove) { this.push(item); } }; Cache.prototype.printLast = function() { if (this.length <= 0) { return } console.log(this[this.length - 1].text); } let test = new Cache(); test.add({foo:'bar', text: 'cake' }); test.add({baz:'bat', doNotRemove: true}); test.add({free:'hugs', text: 'hello'}); test.printLast(); console.log(test);
After some discussions here I was able to build a solution satisfied both of the requirements: keep original ES6 class as a state for new functionality and have this new functionality on the prototype as well as it is for the Array.prototype methods. 经过一些讨论后,我能够构建一个满足这两个要求的解决方案:将原始ES6类保持为新功能的状态,并在原型上使用这个新功能,以及Array.prototype方法。
class CacheProto {
add(item) {
if(!item.doNotRemove)
this.push(item)
}
printLast() {
if(this.length > 0)
console.log(this[this.length - 1].text)
}
}
function Cache() {
const instance = [];
instance.push.apply(instance, arguments);
Object.setPrototypeOf(instance, Cache.prototype);
return instance;
}
Cache.prototype = Object.create(Array.prototype);
Object.getOwnPropertyNames(CacheProto.prototype).forEach(methodName =>
Cache.prototype[methodName] = CacheProto.prototype[methodName]
);
The only difference between this CacheProto
and the original class from the Question is that the CacheProto
class does not extend the Array
. 此CacheProto
与Question中的原始类之间的唯一区别是CacheProto
类不扩展Array
。
The end plunker could be obtained here . 可以在这里获得末端接收器。 It contains this solution and all intermediate variants. 它包含此解决方案和所有中间变体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.