Function
extend (mixins, arguments) public
Defined in packages/@ember/object/core.ts:618
- mixins
- Mixin
- One or more Mixin classes
- arguments
- Object
- Object containing values to use within the new class
Creates a new subclass.
1 2 3 4 5 6 7 |
import EmberObject from '@ember/object'; const Person = EmberObject.extend({ say(thing) { alert(thing); } }); |
This defines a new subclass of EmberObject: Person
. It contains one method: say()
.
You can also create a subclass from any existing class by calling its extend()
method.
For example, you might want to create a subclass of Ember's built-in Component
class:
1 2 3 4 5 6 |
import Component from '@ember/component'; const PersonComponent = Component.extend({ tagName: 'li', classNameBindings: ['isAdministrator'] }); |
When defining a subclass, you can override methods but still access the
implementation of your parent class by calling the special _super()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import EmberObject from '@ember/object'; const Person = EmberObject.extend({ say(thing) { let name = this.get('name'); alert(`${name} says: ${thing}`); } }); const Soldier = Person.extend({ say(thing) { this._super(`${thing}, sir!`); }, march(numberOfHours) { alert(`${this.get('name')} marches for ${numberOfHours} hours.`); } }); let yehuda = Soldier.create({ name: 'Yehuda Katz' }); yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!" |
The create()
on line #17 creates an instance of the Soldier
class.
The extend()
on line #8 creates a subclass of Person
. Any instance
of the Person
class will not have the march()
method.
You can also pass Mixin
classes to add additional properties to the subclass.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import EmberObject from '@ember/object'; import Mixin from '@ember/object/mixin'; const Person = EmberObject.extend({ say(thing) { alert(`${this.get('name')} says: ${thing}`); } }); const SingingMixin = Mixin.create({ sing(thing) { alert(`${this.get('name')} sings: la la la ${thing}`); } }); const BroadwayStar = Person.extend(SingingMixin, { dance() { alert(`${this.get('name')} dances: tap tap tap tap `); } }); |
The BroadwayStar
class contains three methods: say()
, sing()
, and dance()
.