Functions that Return Objects

In addition to using constructor functions and the new operator to create objects, you can also use a normal function and create objects without new. You can have a function that has an object as a return value.

For example, here's a simple factory() function that produces objects.

function factory(name) {
    return {
        name: name

Using the factory():

var o = factory('one');


You can also use constructor functions and return objects which means you can modify the default behavior of the constructor function.

The normal constructor scenario:

function C() {this.a = 1;}

var c = new C();

But now look at this scenario:

function C2() {this.a = 1; return {b: 2};}

var c2 = new C2();

typeof c2.a


Instead of returning the object this, which contains the property a, the constructor returned another object that contains the property b. This is possible only if the return value is an object. Otherwise, if you try to return anything that is not an object, the constructor will proceed with its usual behavior and return this.

Related Tutorial
Follow Us #