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) { this.name = name; } var person = new Person('John Smith'); console.log(person.name);
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.
- Creates new native object and initializes the __proto__ of object by function.prototype.
- Calls function, applying newly created object as value for
this.
- 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.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)