Is there a difference between calling a javascript function with or without the new keyword? For instance if I had the function:
function computer(){
this.hardDrive = "big";
this.processor = "fast";
}
and I then call it in two different ways:
var hp = computer();
var hp = new computer();
what is going to be the difference between the two function calls?
Without
new,thisrefers to the global object, and not any object returned from the function.If you were to execute your code, you’d find that the first
hpwould beundefined, whereas the second would be[object Object]. Further, for obvious reasons, the first would not have a property ofhardDriveorprocessor, but the second would.In the first example, your two properties would have been added to the
windowobject.