0

I have a situation best explained by the code here http://jsfiddle.net/sabithpocker/EsF4R/34/ click on the year to see the issue.

Here is a sample view:

App.myView = Ember.View.extend({
date : new Date(),
dateString : function(){
    return this.get('date').getFullYear();
    }.property().cacheable(),
click : function(e){
    this.$().append('<br/>clicked: now this.get("date") = ' + this.get('date').getFullYear());
    var tempDate = this.get('date');
    tempDate.setFullYear(1988);
    this.$().append("<br/>tempDate :" + tempDate.getFullYear() + " & " + "this.get('date') :" + this.get('date').getFullYear());
    }
});

Inside the click event I am trying to store date to a temp variable for storing, but then when i work on the temp variable the changes are getting reflected on the original. Its what I dont want.

I overcame this by doing:

var tempDate = new Date(this.get('date'));

but what am I doing wrong here?

noah
  • 21,289
  • 17
  • 64
  • 88
sabithpocker
  • 15,274
  • 1
  • 42
  • 75

1 Answers1

1

var tempDate = this.get('date');

tempDate.setFullYear(1988);

this.get('date') returns a reference to the object. You are setting the year on the original Object itself.

When you do this:

var tempDate = new Date(this.get('date'));

You have cloned the original object into a new Object. All further operations will not manipulate the original Object.

Community
  • 1
  • 1
Rajat
  • 32,970
  • 17
  • 67
  • 87
  • 1
    Clone General Object http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object – sabithpocker Jun 25 '12 at 05:29