ES6类扩展了数组:ES5 Babel转堆的解决方法 [英] ES6 Class extends Array: workaround for ES5 Babel transpile
问题描述
我有一些从Array
继承的ES6类:
I have some ES6 class inherited from Array
:
class Cache extends Array {
add(item) {
if(!item.doNotRemove)
this.push(item)
}
printLast() {
if(this.length > 0)
console.log(this[this.length - 1].text)
}
}
以下代码可以正常工作
const myCache = new Cache()
myCache.add({text: 'hello'})
myCache.add({text: 'world'})
myCache.add({text: '!!!', doNotRemove: true})
myCache.printLast() // world
但是我无法使用Babel将其移植到ES5(我知道有一个问题),目前作为一种解决方法,我采用以下方法:
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:
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)
}
这满足上面的代码(myCache = new Cache()
等).但是正如您所看到的,它只是一个扩展的Array实例.
This satisfies the code above (myCache = new Cache()
etc). But as you can see, it's just an Array instance extending.
问题
是否可以使用原始类解决方法?当然,没有extends Array
.能否在原型链上而不是实例上具有add
和printLast
方法以及所有Array.prototype
方法?
Is it possible to have a workaround with original class? Of course, without extends Array
. Is it possible to have add
and printLast
methods and all Array.prototype
methods on the prototype chain, not on instance?
我做了一些 plunker 以便进行可能的研究.
I have made a little plunker for possible research.
推荐答案
在这里进行了一些讨论之后,我可以构建一个满足两个要求的解决方案:将原始ES6类保留为新功能的状态,并在其上启用该新功能原型以及用于Array.prototype方法的原型.
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.
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]
);
此CacheProto
与Question的原始类之间的唯一区别是CacheProto
类不会扩展Array
.
The only difference between this CacheProto
and the original class from the Question is that the CacheProto
class does not extend the Array
.
可以在此处获得最终的塞子.它包含此解决方案和所有中间变体.
The end plunker could be obtained here. It contains this solution and all intermediate variants.
这篇关于ES6类扩展了数组:ES5 Babel转堆的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!