JavaScript Classes

In this article, you will learn about ECMAScript which is a standard for JavaScript. We will only learn about the current ES5 and ES6 features such as JavaScript classes.

When objects are of same type then we want class. But , ES5 only has constructors. For example

Advertisements
function Employee(name, department){
     this.name = name;
     this.department = department;
     this.say = function (){
     alert(“I am “ + this.name);
     }
}

Now, if we want to create objects using the constructor.

let manager = new Employee(‘peter’,’finance’);

Some rules about ES5 Constructor

Rule 1: constructor name has first letter capitalized.
Rule 2: There can only be one constructor.
Rule 3: property has no colon but a “=” sign.
Rule 4: this is used because constructor for same object as Hero.
Rule 5: Function uses function keyword.

In the above example, we have used ‘this’ operator, even through the constructor is not an object and each property has “=” assignment operator rather than the usual (:) colon for properties.

Advertisements

ES 6 Classes

The ES6 have something called class like other programming languages.

The class contains a single constructor which will create multiple objects of same type.

class Employee{
constructor (name, dept){
     this.name = name;
     this.dept = dept;
}
//function in class
say_something(){
     alert(“I am “ + this.name);
     }
}
let manager = new Employee(“peter”,”finance”);

JavaScript Special function (factories)

There is one more method of creating multiple objects. You can create objects using functions that return a value, therefore, we call them factories or factory function.

let supervisor = function(name,dept){
return {
     empName : name,
     empDept: dept
     }
}
Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version