HTML5 Zone is brought to you in partnership with:

I'm software developer and microISV, with a lot of passion to technologies.. having a fun writing code, writing blog posts and giving public speeches. For about 10 years of total experince I've been working in many branches of software development, including management and QA. I try to follow and adopt agile practices and signed up for software craftsmenship manifesto. Alexander is a DZone MVB and is not an employee of DZone and has posted 67 posts at DZone. You can read more from them at their website. View Full User Profile

JavaScript Object Creation by New Operator

  • submit to reddit

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.

Published at DZone with permission of Alexander Beletsky, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)