Over a million developers have joined DZone.
Platinum Partner

JavaScript Object Creation by New Operator

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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) {
    this.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.

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Alexander Beletsky , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}