Friday, December 21, 2012

Use of 'new' keyword in JavaScript

Suppose you have the below function.

var Foo = function () {
  this.val1 = 1;
  this.val2 = 2;

You can execute the function. Foo();

What happens with the execution of the function is it adds up two properties with val1 and val2 to the window since the window is the object that call the function.

Now lets see what happens when you call the function with new key word

var bar= new Foo();

Since JavaScript is an object oriented language and classes are not necessary to create new instance of objects a new object is created as bar with the two properties val1 and val2.


No comments:
Write comments
Recommended Posts × +