Function

extend (mixins, arguments) public

Module: @ember/object
mixins
Mixin
One or more Mixin classes
arguments
Object
Object containing values to use within the new class

Creates a new subclass.

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:

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:

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.

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().

© 2020 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://api.emberjs.com/ember/3.25/functions/@ember%2Fobject/extend