Javascript’s new Operator
Jan 23, 2011
2 minute read

What is it and how can you use it to create new objects from constructor functions?

What’s a constructor function.

There’s really no such thing as a constructor function. There are just functions, that’s it, no different than any other function, except that you the programmer has made it so that it initializes a keyword called this with methods and properties. Here’s the constructor function we will use for the rest of this post.

function Computer(manufacturer, model) {
  this.manufacturer = manufacturer;
  this.model = model;
}

What does new do?

The new operator creates new objects using our constructor function. Let’s start by seeing what happens when we DON’T use the new operator.

var dell_inspiron = Computer('Dell', 'Inspiron');
alert(dell_inspiron); // undefined!

So what happened. Our Computer constructor function ran, it applied the manufacturer and model properties to the this keyword, which should have then populated our dell_inspiron variable. So what the hell was this pointing to? Let’s see what’s happening inside our constructor function:

function Computer(manufacturer, model) {
  alert(this);
  this.manufacturer = manufacturer;
  this.model = model;
}
var dell_inspiron = Computer('Dell', 'Inspiron');
alert(dell_inspiron); // undefined
// notice we now have two additional global objects manufacturer and model... not good
alert(manufacturer); // Dell
alert(model); // Inspiron

So as you can see calling a constructor function without using the new operator, causes our this keyword to point to the global object. Now let’s try using our constructor function with the new operator.

var mac_book_pro = new Computer('Apple', 'Mac Book Pro');
alert(mac_book_pro); // [object OBJECT]
alert(mac_book_pro.manufacturer + ' ' + mac_book_pro.model); // Apple Mac Book Pro

This works as expected, and here’s how. Using the new operator first creates a new blank object. Then, it invokes our constructor function, passing the newly created blank object as the this keyword. Your constructor function then populated the object pointed to by the this keyword with the manufacturer and model properties. When the constructor function ends, it automagically returns the object referenced by the this keyword to the mac_book_pro variable.

Additional Resources

Here’s the example code in jsfiddle you can play with.

http://jsfiddle.net/bawigga/aQb5B/10/

If you want to read more about how the new operator works, I highly recommend the following books: