Alexander Beletsky's development blog

My profession is engineering

JavaScript Object Creation by New Operator

There are different approaches of how to create object in JavaScript. C# and Java programmers are commonly starting with creation by new operator, since it very close to same practice they got used to.

function Person (name) { = name;

var person = new Person('John Smith');

If you try to run this code, you will see ‘John Smith’ in console. Now, try to delete new operator.

Instead of ‘John Smith’ you will see undefined. Why?

The difference is that without new operator it is just function call. During the call `this` points global namespace. If you running the code in browser, global namespace is bind to `window`.

It’s important to understand how new operator works. Internally, operator new is converted to NEW(Person, ‘John Smith’);. It does several things.

  1. Creates new native object and initializes the __proto__ of object by function.prototype.
  2. Calls function, applying newly created object as value for this.
  3. Returns newly created object.

It can be expressed in this kind of pseudo-code:

function NEW(f) {
    var obj = { '__proto__': f.prototype };
    f.apply(obj, arguments.slice(1));
    return obj;

(It’s a bit more complex actually, for details check this great answer on SO).

It means that during function call with `new operator()`, this always points to a new object, created based on function prototype. You can initialize the properties of new object inside the function. It’s no longer a simple function, but it is constructing function, or more simply - constructor.

To distinguish between constructors (that are always supposed to be called with `new`) and simple function, there is a convention to name a constructors with capital first letter (not person(), but Person()), just to give you some tips while you writing the code.

Knowing NEW() details of work and following simple conventions for constructors will help you to understand language better and prevent many stupid errors.