Javascript Constructor, operator "new”

Javascript Constructor, operator "new”

Javascript Constructor, operator "new”


The "new” operator allows creating an instance of a user-defined object type or a built-in operator type that has a constructor function. You can do the following things using the "new” keyword.

  • You can create a blank object of JavaScript;
  • Link this object to another one;
  • Pass the freshly created object from Step 1 like this context;
  • Get back this in case the function doesn’t return its object.

The {...} syntax lets developers create a single object. But, sometimes, it is necessary to generate many similar objects such as menu items, multiple users, and more. You can do it using constructor functions and with the help of the “new” operator.

Two conventions exist, though:

  • You should name them with the capital letter first;
  • You must run them only using the “new” operator

Here is an example:

function Car(name) {

  this.name = name;

  this.isSlow = false;

}

let car = new Car("BMW");

console.log(car.name); // BMW

console.log(car.isSlow); // false

Whenever you invoke a function with “new”, the following actions are taken:

  • Creating a new empty object and assigning to this.
  • Executing the function body. As a rule, it modifies this adding new properties to it.
  • Returning the value of this.

So, new Car(...) acts like this:

function Car(name) {
  // this = {};  (implicitly)
  // add properties to this
  this.name = name;
  this.isSlow = false;

  // return this;  (implicitly)
}

The result of let car = new Car("BMW") will be the same as:

let car = {
  name: "BMW",
  isSlow: false
};

Now, if you wish to create new cars, you can call a new Car("BMW"), a new Car("Mercedes"), etc.

It’s both shorter than using literals and much easier to read.

The aim of the constructors is to implement a reusable object creation code.

In the event of having different lines of code all about creating one complex object, wrap them in the constructor function, as demonstrated in the following example:

new function() { … }

In the event of having different lines of code all about creating one complex object, wrap them in the constructor function, as demonstrated in the following example:

let car = new function () {
  this.name = "BMW";
  this.isSlow = false;

  //another code for creating a car
  //can be complex logic and statements
  //local variables etc
};

Keep in mind that the constructor can’t be called once more, as it is not saved. It is just created and saved.

Return from Constructors

In general, a return statement is not used for constructors. Their primary purpose is writing the overall necessary content into this, and it mechanically becomes turns into the result.

But if a return statement exists, there is a simple rule. It is the following:

  • In case you call to return with an object, the latter is returned instead of this.
  • In case you call to return with a primitive, it will be ignored.

In the following example, return overrides this:

function Car() {

  this.name = "BMW";

  return {

    name: "Mercedes" // returns this object

  }; 

}

console.log(new Car().name); // Mercedes, got that object

And here is another example with an empty return:

function Car() {
  this.name = "BMW";
  return; //returns this
}
console.log(new Car().name); // BMW

Omitting Parentheses

Anyway, it is possible to omit parentheses after the new, if it doesn’t have arguments:

let car = new Car; //no parentheses
// same as
let car = new Car();

Constructor Methods

It is convenient to use constructor functions for creating objects. The constructor functions may include parameters defining how to construct the particular object, and what to put inside of it.

Moreover, it is possible to add to this not only properties but also methods.

For example, a new Car(name) will create an object with a particular name and the sayCarName method:

function Car(name) {

  this.name = name;

  this.sayCarName = function () {

    console.log("Car name is: " + this.name);

  };

}

let bmw = new Car("BMW");

bmw.sayCarName(); // Car name is: BMW

/*

bmw = {

   name: "BMW",

   sayCarName: function() { ... }

}

*/

Summary

Constructors are regular functions, but it is preferred to name them with the capital letter first. They should merely be called with new. A call like this will create an empty this at the beginning and return the populated one at the end.

Constructors are used for creating multiple similar objects as well.

Reactions

Post a Comment

0 Comments

close