1

我只是不明白。我通过扩展数组属性来定义自己的对象

MyObj = Ember.Object.extend({
  id: 0,
  data: []
});

var obj1 = MyObj.create();
obj1.id = 1;
console.log(obj1.data); # will output []
obj1.data.push("a");

var obj2 = MyObj.create();
obj2.id = 2;
console.log(obj2.data); # will output ["a"]
obj2.data.push("b");

console.log(obj1.data); # will output ["a", "b"]

jsbin
我认为 obj1 和 obj2 是完全独立的对象。只是好奇为什么。

4

2 回答 2

4

简短的回答是您在data原型上设置属性,然后在从您的类实例化的对象之间共享。

我在这篇关于 Ember.Object 的文章中更详细地解释了这一点(参见初始化部分):http ://www.cerebris.com/blog/2012/03/06/understanding-ember-object/

于 2013-09-20T18:55:36.057 回答
1

要解决此问题,您需要使用init挂钩来设置data属性。

这是一个示例 JSBin:http: //jsbin.com/ucanam/1103/edit

MyObj = Ember.Object.extend({
  id: 0,
  data: null,
  init : function(){
    this.set('data',[]);
  }
});

var obj1 = MyObj.create();
obj1.id = 1;
console.log(obj1.get('data')); // will output []
obj1.get('data').pushObject("a");

var obj2 = MyObj.create();
obj2.id = 2;
console.log(obj2.get('data')); // will output []
obj2.get('data').pushObject("b");

console.log(obj1.get('data')); // will output ["a"]
console.log(obj2.get('data')); // will output ["b"]
于 2013-09-21T06:04:00.747 回答