0

我有一个最好用这里的代码解释的情况http://jsfiddle.net/sabithpocker/EsF4R/34/ 点击年份查看问题。

这是一个示例视图:

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());
    }
});

在点击事件中,我试图将日期存储到临时变量中进行存储,但是当我处理临时变量时,更改会反映在原始变量上。它是我不想要的。

我通过这样做克服了这个问题:

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

但我在这里做错了什么?

4

1 回答 1

1

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

tempDate.setFullYear(1988);

this.get('date') 返回对对象的引用。您正在原始对象本身上设置年份。

当你这样做时:

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

您已将原始对象克隆为新对象。所有进一步的操作都不会操纵原始对象。

于 2012-06-25T03:49:13.213 回答