Constructor Functions

You can create objects in another way by using constructor functions with new operator.

function Hero() {
    this.occupation = 'Ninja';
}

To create an object using above function, use the new operator.

var hero = new Hero();

hero.occupation;
"Ninja"

The constructor functions accept parameters, which will be useful when creating new objects. You can create different objects using the same constructor.

snippet
function Hero(name) {
    this.name = name;
    this.occupation = 'Ninja';
    this.whoAreYou = function() {
        return "I'm " + this.name + " and I'm a " + this.occupation;
    }
}

Different objects created using the same constructor:

var h1 = new Hero('Michelangelo');
var h2 = new Hero('Donatello');

h1.whoAreYou();
"I'm Michelangelo and I'm a Ninja"

h2.whoAreYou();
"I'm Donatello and I'm a Ninja"

By convention, capitalizing the first letter of your constructor functions differentiates it from a normal function.

When you omit the new operator while calling a function that is designed to be a constructor, it will not behave as you could expect, also this is not an error.

var h = Hero('Leonardo');

typeof h
"undefined"

In the above example as there was no new operator, it didn't create a new object. The function was called like any other function, so h contains the value that the function returns. The function does not return anything (there's no return), so it actually returns undefined, which gets assigned to h. In this case, it refers to the global object.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +