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)
}
}
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:
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). But as you can see, it's just an Array instance extending.
The question
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?
I have made a little plunker for possible research.