1

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?
  }
}

1 Answer 1

2

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:

https://github.com/vuejs/vue/blob/9fbd416635eb3d7b32cd73b7c29f8377003c4dc8/src/core/observer/index.js#L49

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Question was about why Vue switch array. Not about reactivity, pop and push
@user1272025 My answer explains why Vue switches the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.