Reopening Classes and Instances

Reopening Classes and Instances

You don't need to define a class all at once. You can reopen a class and define new properties using the reopen() method.

Person.reopen({
  isPerson: true
});

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

When using reopen(), you can also override existing methods and call this._super.

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

reopen() is used to add instance methods and properties that are shared across all instances of a class. It does not add methods and properties to a particular instance of a class as in vanilla JavaScript (without using prototype).

But when you need to add static methods or static properties to the class itself you can use reopenClass().

// add static property to class
Person.reopenClass({
  isPerson: false
});
// override property of existing and future Person instances
Person.reopen({
  isPerson: true
});

Person.isPerson; // false - because it is static property created by `reopenClass`
Person.create().get('isPerson'); // true

© 2017 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://guides.emberjs.com/v2.13.0/object-model/reopening-classes-and-instances

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部