3

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?

dagronlund
  • 1,472
  • 3
  • 12
  • 14
  • 1
    Duplicate of [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) and [Is JavaScript's new keyword considered harmful?](http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful) and [Using Object.create instead of new](http://stackoverflow.com/questions/2709612/using-object-create-instead-of-new) – Phrogz Apr 26 '12 at 01:26
  • See also [Create an empty object in JavaScript with {} or new Object()?](http://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object). – Phrogz Apr 26 '12 at 02:32

2 Answers2

8

Without new, this refers 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 hp would be undefined, whereas the second would be [object Object]. Further, for obvious reasons, the first would not have a property of hardDrive or processor, but the second would.

In the first example, your two properties would have been added to the window object.

Sampson
  • 251,934
  • 70
  • 517
  • 549
  • 1
    isn't it that the `this` in the first case (no `new`) is the `window` global object? and executing the function adds `hardDrive` and `processor` to the global object? – Joseph Apr 26 '12 at 01:27
  • 1
    Not at all. ECMA-262 defines [execution context](http://es5.github.com/#x10.3), it is the only context in which the word is used. An execution context consists of all the local variables, parameters, scope chain, etc. and includes *this*. The value that *this* is set to by the call has nothing at all to do with the execution context that the call was made from, or the function context that is created by a call. All you know is that in global code, *this* references the global object. In any other context, it can reference (almost) anything, including the global object. – RobG Apr 26 '12 at 07:09
1

The first one, not using new, will run with this referring to the window object. The second one, using new, will create a new empty object, and that object will be the this within the function.

Wyzard
  • 31,764
  • 3
  • 60
  • 78