Javascript - Problems with Constructors

Introduction

By using constructors the methods are created once for each instance.

Methods inside constructor function are created each time you call the constructor.

Functions are objects in JavaScript, so every time a function is defined, it's actually an object being instantiated.

The constructor actually looks like this:

function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = new Function("console.log(this.name)");  //logical equivalent
}

Each instance of Person gets its own instance of Function that displays the name property.

It doesn't make sense to have two instances of Function that do the same thing.

You can work around this limitation by moving the function definition outside of the constructor:

function Person(name, age, job){
    this.name = name;
    this.age = age;

    this.job = job;
    this.sayName = sayName;
}

function sayName(){
    console.log(this.name);
}

var person1 = new Person("First", 29, "writer");
var person2 = new Person("Tom", 27, "Doctor");

Here, the sayName() function is defined outside the constructor.

Inside the constructor, the sayName property is set equal to the global sayName() function.

Since the sayName property now contains just a pointer to a function, both person1 and person2 end up sharing the sayName() function in global scope.

This solves the problem of having duplicate functions but also adds a function of a certain object to the global scope.

Related Topic