0

I wrote a function:

getClassTable () {
  var classNormalData = this.classData.normal,
      alterClasses = this.classData.alter.classes,
      classTable = [];

  for(var day in classNormalData) {
    classTable.push(classNormalData[day]);
  }

  if(alterClasses != []) {
    alterClasses.forEach(function(item, index) {
      var date = item.time,
          lesson = item.lesson;
      for(var i = 0; i < 4; i++){
        var time = this.dates[i],
            classes = classTable[i][lesson];
        if(time == date) {
          classes.subject = item.subject;
          break;
        }
      }
    }, this)
  }
  this.classTable = classTable;
}

}

but when the classes.subject = item.subject works, somethings went wrong. It seemed changethis.classDatadirectly. The variables classNormalData classTable didn' t work well. Why?

Ps: this.classData is defined here

computed: {
  classData () {
    return this.$localStorage.get('classList');
  },
}
Xile
  • 21
  • 1
  • 5
  • Can you also add which ones are your vue variable, possible to reproduce in jsfiddle, any specific error you are getting in console? – Saurabh Dec 21 '16 at 04:11
  • Thank you. I have known how to solve it just now. It is because that when I set a obj as a variable, it actually links to the original object. I find a approach is to apply `var newObj = JSON.parse(JSON.stringify(obj))` – Xile Dec 21 '16 at 04:29

1 Answers1

0

In javascript, variables as pointers to objects. When you assigning to a variable, you are not modifying any objects, merely repointing your variable to a different object. so if you modify the assigned object, original as well will change.

To overcome this, you have to create a new object which is clone of original object. There are multiple way to do this, one way as you have pointed out in comment:

var newObj = JSON.parse(JSON.stringify(obj))

There are better and efficient ways to do this, like using Object.assign:

var newObj = Object.assign({}, obj)

underscore and lodash also provides their clone methods.

You can see this answer for other solutions.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244