Javascript - Constructors vs Functions


The only difference between constructor functions and other functions is the way in which they are called.

Constructors are just functions.

There is no special syntax to define a constructor.

Any function that is called with the new operator acts as a constructor.

Any function called without new operator acts a normal function.

For instance, the Person() function may be called in any of the following ways:

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

    this.job = job;
    this.sayName = function(){
//use as a constructor
var person = new Person("First", 29, "writer");
person.sayName();   //"First"

//call as a function
Person("Tom", 27, "Doctor");  //adds to window/global object
window.sayName();   //"Tom"

//call in the scope of another object
var o = new Object();, "Jack", 25, "Nurse");
o.sayName();    //"Jack"

The first part uses Person function as a constructor and it creates a new object via the new operator.

The second part uses Person() function as normal function without the new operator: the properties and methods are added to the window object.

The this object points to the Global object (window in web browsers) when a function is called without an explicitly set this value.

So after the function is called, the sayName() method can be called on the window object in broswer, and it will return "Tom".

The Person() function can also be called within the scope of a particular object using call() or apply().

In this case, it's called with a this value of the object o, which then gets assigned all of the properties and the sayName() method.