How to define a new class in Ember.js ?
Last Updated :
23 Feb, 2022
Native classes in JavaScript were added in ES6 (or ES2015) as a provision of means to bind data and functions together. They allow us to create a user-defined data type that consists of its own unique data members and member functions, which can be accessed in the code by using their instances (or objects).
Approach: To define a new class in Ember.js, we have to use the class keyword along with the name of the class. Then we have to declare the class variables and member functions inside curly braces “{ }”. We can also write the default parameter values of the class by using the in-built constructor function. After that, we can create an object of that class by using the “new” keyword and initializing the constructor values in the parameter of the object definition like – new Car(carName, carModel, carColor); where the variables inside the brackets are the parameters of the object declaration.
Syntax:
// Class declaration
class name_of_class {
constructor(something, random) {
this.something1 = something1;
this.random2= random2;
}
}
We can define 6 types of elements in a certain class in Ember.js:
- Class Constructor
- Member Data Fields (Variables)
- Member Functions
- Accessors (Getters and Setters)
- static
- Decorators
Example 1:
Javascript
class Car {
constructor(name, model, color) {
this .name = name;
this .model = model;
this .color = color;
}
print() {
console.log(`Name of Car: ${ this .name}`);
console.log(`Model of Car: ${ this .model}`);
console.log(`Color of Car: ${ this .color}`);
}
}
let carName = "BMW" ;
let carModel = "E6" ;
let carColor = "Matte Black" ;
let randomCar = new Car(carName, carModel, carColor);
randomCar.print();
|
Output:
The output of Ember.js class definition example 1
Example 2:
Javascript
class Dog {
constructor(name, breed) {
this .name = name;
this .breed = breed;
}
print() {
console.log(`Name of Dog: ${ this .name}`);
console.log(`Breed of Dog: ${ this .breed}`);
}
}
let dogName = "Tommy" ;
let dogBreed = "German Shepherd" ;
let randomDog = new Dog(dogName, dogBreed);
randomDog.print();
|
Output:
The output of Ember.js class definition example 2
Share your thoughts in the comments
Please Login to comment...