Ember学习(8):REOPENING CLASSES AND INSTANCES

英文原址:http://emberjs.com/guides/object-model/reopening-classes-and-instances/


你不需要一次就完成类全部内容的定义,通过reopen方法,你可以重新打开一个类定义并且添加新的属性。

1
2
3
4
5

Person.reopen({
 
isPerson: true
});

Person.create().get(
'isPerson') // true


当使用reopen时,你也可以重写已有的方法,通过调用this._super调用之前的版本

1
2
3
4
5
6

Person.reopen({
 
// override `say` to add an ! at the end
 
say: function(thing) {
   
this._super(thing + "!");
  }
});

reopen方法是用于给类添加新的实例方法和属性的,这些新添加的属性和方法会被所有该类的实例所共享,它不是仅仅只给该类的某个特定的实例添加方法和属性(好比普通的Javascript下不使用prototype的情况)

 

如果你需要给类本身添加新的类属性或者类方法,你可以使用reopenClass

1
2
3
4
5
6
7

Person.reopenClass({
 
createMan: function() {
   
return Person.create({isMan: true})
  }
});

Person.createMan().get(
'isMan') // true


你可能感兴趣的:(Ember)