JavaScript: What's Constructor? What Does Keyword “new” Do?

, , …,

One way to create a object is using the keyword new, in this syntax: new function name(…);), where function name can be ANY function. (for 2 other ways of creating objects, see: JavaScript: Creating Object with Object.create())

What's a Constructor?

What's a constructor?

When a function is used in new function name(…), the function is called a constructor.

Builtin Constructors

The most common use of new is to create a builtin object using builtin constructor, such as Date object. Example:

// create a new Date object
var x = new Date();
console.log(x); // Mon, 05 Aug 2013 02:26:25 GMT
JavaScript Construtors
ObjectLiteral Expression SyntaxConstructor SyntaxNotes
Generic Object{…}new Object(…)〔☛ What's Object in JavaScript?
Array[…]new Array(…)〔☛ JavaScript Array Methods
Functionfunction (…) {…}new Function(…)〔☛ JavaScript Function Constructor
Regex/…/…new RegExp(…)〔☛ JavaScript Regex Object
Datenew Date(…)No litral expression.
MathNo constructor. Similar to “static class” in Java. Use like this Math.PI, Math.floor(4.2)
JSONNo constructor. ⁖ JSON.parse(…), JSON.stringify(…)

Primitimive Type Wrapper Constructors

The following are constructors for primitive types. (when you call a method on a primitive type, such as " somestring ".trim(), the string is temporarily converted to a string object. That's why it has methods.)

ObjectLiteral Expression SyntaxConstructor SyntaxNotes
Number{3, -3, 3.7, …}new Number(…)Wrapper
String"…"new String("…")Wrapper. 〔☛ JavaScript String Methods
Boolean{true, false}new Boolean(…)Wrapper

For builtin objects, you should use the literal expression whenever possible.

Creating Object with User Defined Constructor

You can create a object by using the keyword new with this syntax new function name(…);, where function name is ANY function.

// example of creating a object with user defined constructor function

// define a function.
function FF () {
    this["b"] = 4; // adding a property
    // note: no “return” statement
}

// create a new object
var x = new FF(); // function used this way is called “constructor”

console.log(x);                 // { b: 4 }
console.log(typeof x);          // object
console.log(x.b);               // 4

What Does “new” Do Exactly?

Here's what the new keyword do. Let's say we have new F().

  1. JavaScript creates a new empty object with its parent set to the F.prototype. Let's call this new object “tempObj”. (this is similar to calling var tempObj = Object.create(F.prototype). 〔☛ Creating Object with Object.create()〕 〔☛ Understanding Prototype & Inheritance〕)
  2. The function F is executed, with F's this keyword set to “tempObj”. 〔☛ What's “this” Keyword do?
  3. If F does not have a return statement, or it does but returns a value that is not a object (⁖ a primitive such as a number) then the “tempObj” is the result. If F returns a value that is a JavaScript object, then this object is the result. 〔☛ What's Object in JavaScript?

ECMAScript §11#sec-11.2.2

Return Statement in a Constructor Function

It must be emphasized, that whether constructor function has return statement is critical.

When function is used as a constructor (⁖ new F()), the result object critically depends whether the constructor returns a JavaScript object.

// example showing difference of constructor with different type of return value

var F1 = function () { this["b"] = 4; }
var F2 = function () { this["b"] = 4; return 3; }
var F3 = function () { this["b"] = 4; return {"c":7}; }

var x1 = new F1();
var x2 = new F2();
var x3 = new F3();

console.log(x1); // prints { b: 4 }
console.log(x2); // prints { b: 4 }
console.log(x3); // prints { c: 7 }

What's the Prototype of a Object Created with a Constructor?

From the above, you should be able to figure it out. But, here's explicit explanation:

Here's a example showing the prototype of the new object created by a constructor that doesn't have return statement.

// showing the prototype of a object created by a constructor that doesn't have a return statement
var FF = function (xx) { this["yy"] = xx; };
var oo = new FF(3);
console.log( Object.getPrototypeOf(oo) === FF.prototype ); // true

Here's a example showing the prototype of the new object created by a constructor that returns a object.

// showing the prototype of a object created by a constructor that returns a object

// this function returns a object
var FF = function (xx) { return {"yy":3}; };

var oo = new FF(3);

// the parent of newly created object is NOT FF.prototype
console.log( Object.getPrototypeOf(oo) === FF.prototype ); // false

// because the function FF returns a object
// so, the newly created object is whatever the function returned.
// so, its parent is whatever the returned object's parent
// in this case, the object is created by literal expression {…}, and by default its parent is Object.prototype
console.log( Object.getPrototypeOf(oo) === Object.getPrototypeOf({}) ); // true
console.log( Object.getPrototypeOf(oo) === Object.prototype ); // true

〔☛ JavaScript Tutorial: Understanding Prototype & Inheritance

Parenthesis Optional for Constructor Call with No Args

When a function is used as a constructor and without argument, the round brackets are optional. Example:

// the following 2 are syntactically equivalent
var xx = new F();
var xx = new F;

Constructor Name Should Start with Capital Letter

By convention, functions designed to be used as constructor start with a capital letter.

This is important, because: ① in JavaScript, any functions can be used as a constructor, technically. ② functions designed to be constructors have very different behavior than normal functions.

blog comments powered by Disqus