0

Constructors are like normal functions in javascript.

function Vehicle (param1, param2){
  this.param1 = param1;
  this.param2 = param2;
}

Why do we need to call them with new operator

1) var car = new Vehicle ('abc' , 'def');

Why not like this and explicitly return 'this' ?

2) var car = Vehicle('abc' , 'def'); //Like a simple function call.

In 2) object is not created. and car.param1 gives undefined.

What is it that "new" is doing behind the scene?

Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
  • 1
    2) would probably work if you'd type `return this` at the end of the function. A constructor is a function that has no return type, because it creates an instance of the type it is a constructor for. When you use `new`, you tell the system that you're trying to call a constructor rather than a normal function. – Glubus Nov 27 '17 at 13:10
  • Because this is how Javascript constructors works, otherwise you could use a **function** just like @Glubus suggested. [I think you should read the doc, before asking new questions.](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) – Dwhitz Nov 27 '17 at 13:13

1 Answers1

0

calling function using new will convert your function from this

function Vehicle (param1, param2){
  this.param1 = param1;
  this.param2 = param2;
}

to this

function Vehicle (param1, param2){
  var this={};
  this.param1 = param1;
  this.param2 = param2;
  return this;
}

In 2) object will be created. and car.param1 wont come undefined . If you write function like this

function Vehicle (param1, param2){
      var obj={};
      this.param1 = param1;
      this.param2 = param2;
      return obj;
    }