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:
// Defining the class class Car { // Initializing a constructor
constructor(name, model, color) {
this .name = name;
this .model = model;
this .color = color;
}
// Defining a member function
print() {
console.log(`Name of Car: ${ this .name}`);
console.log(`Model of Car: ${ this .model}`);
console.log(`Color of Car: ${ this .color}`);
}
} // Declaring parameter variables let carName = "BMW" ;
let carModel = "E6" ;
let carColor = "Matte Black" ;
// Creating an instance of the class let randomCar = new Car(carName, carModel, carColor);
// Printing the output to the console randomCar.print(); |
Output:
Example 2:
// Defining the class class Dog { // Initializing a constructor
constructor(name, breed) {
this .name = name;
this .breed = breed;
}
// Defining a member function
print() {
console.log(`Name of Dog: ${ this .name}`);
console.log(`Breed of Dog: ${ this .breed}`);
}
} // Declaring parameter variables let dogName = "Tommy" ;
let dogBreed = "German Shepherd" ;
// Creating an instance of the class let randomDog = new Dog(dogName, dogBreed);
// Printing the output to the console randomDog.print(); |
Output: