Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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');
  },
}
share|improve this question
    
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 4: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 4:29

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.