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');
o.name
"one"
o.constructor

Object()

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();
c.a
1

But now look at this scenario:

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

var c2 = new C2();

typeof c2.a
"undefined"

c2.b
2

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
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +