Thursday, January 23, 2014

Constructor Function in JavaScript

When you invoke the Constructor Function with new, the following happens inside the
function:
  1. An empty object is created and referenced by this variable, inheriting the prototype of the function.
  2. Properties and methods are added to the object referenced by this.
  3. The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

/**
 * @constructor
 * @param{string} name
 */
var Person = function( name ) {

// 1
// var this = Object.create(Person.prototype);

// 2
// add properties and methods
this.name = name;
this.say = function( ) {
return "I am " + this.name;
};

//3
// return this;
};

var joe = new Person( "Joe" );
typeof joe === 'object'; // true
joe.constructor === Person; // true
joe instanceof Person; // true


Constructor’s Return Values

When invoked with new, a constructor function always returns an object. Constructors implicitly return this, even when you don’t have a return statement in the function. But you can return any other object of your choosing.

Is it confusing?
/**
 * @constructor
 * @param{string} name
 */
var Person = function( name ) {
this.name = name;
return name;
}

var joe = new Person( "joe" );
typeof joe === 'object'// true
joe.name // joe


Let's see what it says ECMAScript Language Specification:


When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:
  1. Let obj be a newly created native ECMAScript object.
  2. Set all the internal methods of obj as specified in 8.12.
  3. Set the [[Class]] internal property of obj to "Object".
  4. Set the [[Extensible]] internal property of obj to true.
  5. Let proto be the value of calling the [[Get]] internal property of F with argument "prototype".
  6. If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.
  7. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in Object prototype object as described in 15.2.4.
  8. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
  9. If Type(result) is Object then return result.
  10. Return obj.


Reference