Reputation: 21
I'm extending builtIn Array with my class MyArray When i try to store MyArr to Vuex, I loose instance, and get bultIn Array
What's wrong?
class MyArray extends Array{/*some methods*/}
const state = {
arr: new ModuleOperationArray(),
}
const mutations = {
setArr: (state) => {
console.log(state.arr instanceof MyArray); //false -- WHY?
let arr = new MyArray();
console.log(arr instanceof MyArray); //true -- expectedly
state.arr = arr;
console.log(state.arr instanceof MyArray); //false -- WHY?
}
}
Upvotes: 1
Views: 53
Reputation: 29092
To make arrays reactive Vue needs to patch various methods such as push
and pop
with its own versions. These work just the same as the originals while triggering the reactivity system.
To achieve this patching quickly Vue switches out the prototype of the Array to its own extended version. See:
The specifics vary depending on browser support.
The instanceof
operator determines its value based on the prototype chain. Once Vue has made the switch your array will no longer have MyArray
in its prototype chain.
Upvotes: 1