Using the new Javascript keyword

Is there any difference between calling a javascript function with or without a keyword? For example, if I had a function:

function computer(){
  this.hardDrive = "big";
  this.processor = "fast";
}

and I then call it two different ways:

var hp = computer();
var hp = new computer();

what's the difference between two function calls?

+3
source share
2 answers

Without new, thisrefers to the global object, and not to any object returned by the function.

If you had to execute your code, you will find that the first hpwill be undefined, while the second will be [object Object]. Further, for obvious reasons, the former will not have the property hardDriveor processor, but the latter will.

window.

+8

, new, this . , new, , this .

+1

All Articles