What is new?

This can be omitted at a first reading, and omitted altogether if you never have to deal with code that uses the new operator. If you do, then you must read about the missing new problem.

JavaScript has an object tree. This is a fundamental language feature. The new operator is a way of adding objects to the tree. The create function, which is built-in to the latest version of JavaScript, can be defined in terms of new, and vice versa.

Test code

TEST('new-operator', function()
{
    // A 'traditional class'.  It records 'this' as a side effect.
    var this_in_Fn;
    var Fn = function(){
        this_in_Fn = this;
    };

    // Call the 'class' without the 'new'.
    this_in_Fn = null;          // Clear any previous value.
    var non_instance = Fn();
    assert( non_instance === undefined );
    assert( this_in_Fn.telltail === 'global');

    // Call the 'class' with the 'new'.
    this_in_Fn = null;          // Clear any previous value.
    var instance = new Fn();
    assert( instance === this_in_Fn );
    assert( instance.telltail === undefined );

    // Demonstrate that instance is a descendant of Fn.prototype.
    Fn.prototype.telltail = 'instance-of-Fn';
    assert( instance.telltail === 'instance-of-Fn' );

    // We can give Fn a new prototype.
    instance.new_telltail = 'child-of-instance';
    Fn.prototype = instance;

    // And now an instance of Fn has two telltails.
    var second_instance = new Fn();
    assert( second_instance.telltail === 'instance-of-Fn' );
    assert( second_instance.new_telltail === 'child-of-instance' );

});

Discussion

By changing the prototype object of Fn we start building a tree of objects.

There is a built-in relation between an object and its parent. There is no relation between the object and its constructor, here called Fn, except that at the time of construction the parent of the object is Fn.prototype.

The exact rules for the behaviour of new are complicated and not given here.

No missing new warning

We saw that when Fn is called without the new then during its execution the value of this is the global object. If the constructor Fn mutates this (and almost every constructor does), then it is the global object that is mutated.

This is very bad:

  1. You may clobber someone elses data.
  2. Someone else may clobber your data.
  3. If you create two instances, you will clobber your own data.
  4. Testing for this error involves extra work.
  5. Bugs that arise from this error can appear random and can be hard to find.

Note

Crockford writes A much better alternative is to not use new at all.”