Constructor Function ?

A Constructor Function :
Consider the following function and call to the function:

  function Foo(){
    this.bar = "baz";
    console.log(this);
  }
  
  var f = new Foo();
  console.log(f.bar);

In this example, the “Foo” function is being used as a constructor function – a function that is designed to create object instances. Note that there is nothing in the JavaScript language that says this is a constructor function, nor is there anything that says a function must be set up in a certain way in order to be a constructor function.There are a few subtle hints in the patterns of JavaScript usage that tell us this is a constructor function.
1) The first hint is that the function name is capitalized. 2)The second is the assignment of “this.bar” in the function. 3)The final hint is the use of the “new” keyword.

From the above code, You will see two things in the console. The first of which will be the logging of “this” from the function itself. That call will produce an object in the console, which contains an attribute of “bar” assigned to the value of “baz”. The second thing you will see is the string “baz”, logged from the “f.bar” attribute, after the object is instantiated.

But … Why?

When a function is used as a constructor (and keep in mind that any function can be used as a constructor – though the results are not guaranteed if the function was not designed for this), the value of “this” within that function becomes something new and unique. It becomes an object instance, of the “type” that the function represents.

In the above example, then, the value of “this” is a new instance of a “Foo” object. When the function exits, the value of “this” is returned automatically – you don’t need to return anything manually.

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Javascript Tagged with: