Learn Javascript Constructor, operator "new”

Learn Javascript Constructor, operator "new”

Namaskar.Gif GIF - Namaskar Modi Pm GIFs

Namaskar! this is Aryan Sharma's blog, and I hope you're all doing well & great.

Welcome to another blog of this JavaScript course.

📍You can find my blogshere↗️

Let's get started!

new operator

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 create a blank object of JavaScript;

  • Link this object to another one;

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.

Syntax:

function Car(name) {
  this.name = name;
  this.isSlow = false;
}
let car = new Car("BMW");
console.log(car.name); // BMW
console.log(car.isSlow); // false

new function() { … }

If you have many lines of code that are all concerned with building a single complicated object, encapsulate them in the constructor function, as this example illustrates:

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

test: new.target

Inside a function, we can check whether it was called with new or without it, using a special new.target property.

It is undefined for regular calls and equals the function if called with new

Return from Constructors

Constructors do not have a return statement. They store all necessary stuff into this, and it automatically becomes the result.

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

  • In case you call return with an object, the latter is returned instead of this.

  • In case you call return with a primitive, it will be ignored.

function Car() {
  this.name = "BMW";
  return {
    name: "Mercedes" // returns this object
  }; 
}
console.log(new Car().name); // Mercedes, got that object

And now, here is another example with an empty return:

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

Omitting Parentheses

We can omit the parenthesis if it does not have arguments.

let name = new Name; 
// Both are same
let name = new Name();

Constructor Methods

Constructor functions are a convenient way to create things. Constructor functions can include parameters that specify what goes into and how to build a certain object.

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();

& that's it....End of blog

See u in the next blog...Stay tuned🎶

Don't forget to follow me on:
Twitter And LinkedIn