Vimal Vimal -5 years ago 144
Javascript Question

What are all the difference between function and constructor function in javascript?

In this blog author is saying below function is constructor function

function Cat(name, color) { = name;
this.color = color;
Cat.prototype.age = 0;

var catC = new Cat("Fluffy", "White");

The instances of
function has name and color property. Is this the only difference between normal and constructor function ?

Answer Source

A constructor function is a normal function.

What makes the difference here is the use of the new operator which makes the context (this) in the function the new instance, thus letting it take the two properties, and returns this new instance.

Without the new operator, the context would have been the external one (window if your code is in the global scope in loose mode, undefined if in strict mode).

That is, if you omit the new

var catC = Cat("Fluffy", "White");

the function "works" (if you're not in strict mode) but you have two different results :

  • catC is undefined as your function returns nothing
  • name and color are now properties of the external scope

The whole magic, thus, is in the new operator :

When the code new foo(...) is executed, the following things happen:

A new object is created, inheriting from foo.prototype.

The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

When I said it's a normal function I, I omitted one thing : the intent of the developer. You usually define functions to be either called as constructors (i.e. with new) or not. In the first case you most often use the arguments to initialize the fields of the instance (using = ...) and you often follow by adding functions to the prototype (as you did) so that they become available for all instances.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download