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();


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

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

Different objects created using the same constructor:

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

"I'm Michelangelo and I'm a Ninja"

"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

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 #
Contents +