AppDividend
Latest Code Tutorials

Javascript Constructor Tutorial | Constructor in Javascript Example

0

Javascript Constructor Tutorial | Constructor in Javascript Example is today’s topic. A constructor method is an excellent method for creating and initializing an object produced within the class.

There can be only one particular method with a name “constructor” in the class. Having more than one occurrence of the constructor method in the class will throw the SyntaxError error.

The constructor can use a super keyword to call a constructor of the parent class.

If you do not specify a constructor method, a default constructor is used.

Javascript Constructor Tutorial

It is considered the good practice to name the constructor functions with an upper-case first letter.

The way to create the “object type,” is to use an object constructor function.

In the example above, function Investor() is the object constructor function.

Objects of the same type are created by calling a constructor function with a new keyword.

let st2 = new Investor("Eleven", 15);
let st3 = new Investor("Robin", 21);

#The this Keyword

In JavaScript, this is the object that “owns” the code.

The value of this, when used in the object, is an object itself.

In the constructor function, this does not have a value. It is the substitute for the new object. The value of this will become a new object when a new the object is created.

One thing you can note that here is that this is not a variable. It is a keyword. You cannot change the value of this.

#Adding a Property to an Object

Adding the new property to an existing object is easy. See the following code.

function Investor(name, age) {
  this.name = name;
  this.age = age;
}

let st2 = new Investor("Eleven", 15);
let st3 = new Investor("Robin", 21);

st2.nationality = 'British';
console.log(st2);

See the output.

➜  es git:(master) ✗ node app
Investor { name: 'Eleven', age: 15, nationality: 'British' }
➜  es git:(master) ✗

#Adding a Method to an Object

Adding the new method to an existing object is easy. See the following code.

function Investor(name, age) {
  this.name = name;
  this.age = age;
}

let st2 = new Investor("Eleven", 15);
let st3 = new Investor("Robin", 21);

st2.nationality = 'British';

st2.eleven = function () {
  return this.name +' is '+ this.age + ' years old';
}
console.log(st2.eleven());

See the following output.

➜  es git:(master) ✗ node app
Eleven is 15 years old
➜  es git:(master) ✗

#Adding a Method to a Constructor

You can also define the constructor methods inside the constructor function.

See the following code example.

function Investor(name, age) {
  this.name = name;
  this.age = age;
  this.eleven = function () {
    return this.name +' is '+ this.age + ' years old';
  }
}

let st2 = new Investor("Eleven", 15);
let st3 = new Investor("Robin", 21);

st2.nationality = 'British';
console.log(st2.eleven());

See the following output.

➜  es git:(master) ✗ node app
Eleven is 15 years old
➜  es git:(master) ✗

You cannot add the new method to an object constructor the same way you add the new method to the existing object. Adding new methods to an object constructor must be done inside a constructor function.

#Built-in JavaScript Constructors

JavaScript has built-in constructors for native objects like the following.

let a1 = new Object();
let a2 = new String();
let a3 = new Number();
let a4 = new Boolean();
let a5 = new Array();
let a6 = new RegExp();
let a7 = new Function();
let a8 = new Date();

As you can see above, the JavaScript has object versions of a primitive data types String, Number, Array, and Boolean. But there is no reason to create the complex objects. Primitive values are much faster.

#Constructor in JavaScript with ES6

In ES6, we can create the classes. If you’ve come from the OOP language like Python or PHP, this will be familiar to you. Look at the following code.

class StrangerThings {
  constructor(name, age, networth) {
    this.name = name;
    this.age = age;
    this.networth = networth;
  }

  get detail() {
    return this.name + ' ' + this.age +' '+ this.networth;
  }
}
const eleven = new StrangerThings("Millie", 15, 4);
console.log(eleven);

See the following output.

➜  es git:(master) ✗ node app
StrangerThings { name: 'Millie', age: 15, networth: 4 }
➜  es git:(master) ✗

The class function creates the template that we can use to create the objects later. The constructor() method is the special method called when the instance of a StrangerThings class is created.

  1. A function keyword is replaced with the class keyword
  2. There’s a particular function named ‘constructor’ where the initialization of an object is done. Hence whatever is the present in the body of a traditional function gets shifted to a ‘constructor’ function. It is called whenever a new object of that ‘class’ is created.
  3. Any method created inside the class body and it is considered a ‘member’ of the class.

#The super and extends keywords

You can create the subclass or a child class using the ‘extends’ keyword. The subclass can add its logic along with the data inherited from the ‘base’ class.

See the following code example.

class Millie {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}
class Eleven extends Millie {
  constructor(character, power = 'telekenesis') {
    super(character);
    this.power = power;
  }
  speak(){
    console.log('UK Accent');
  }
}
let el = new Eleven('Friends Don\'t lie');
el.speak();

See the following output.

➜  es git:(master) ✗ node app
El has UK Accent
➜  es git:(master) ✗

Finally, Javascript Constructor Tutorial | Constructor in Javascript Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.