Instance creation in Javascript


There is a lot of confusion about instance creation in javascript .It is a common interview question.hence my attempt at providing some clarity .


var constructorFn = function(){
this.variable = "Hello World"
}
var obj = new constructorFn();

If you print obj in the console,you will see something like this


constructorFn {variable: "Hello World"}

This basically means that the obj is of type constructorFn . And the obj has 1 property.The “this” object is set to the new object itself


obj instanceof constructorFn

The above statement returns true .

Next Part:


var constructorFn = function(){
this.variable = "Hello World";
return "returned value";
}
var obj = new constructorFn();

On printing obj we see.

constructorFn {variable: "Hello World"}

So our function now has a return value.If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. So u see the constructor of your object in console

More modification


var constructorFn = function(){
this.variable = "Hello World";
return {"value":"hello inner world"}
}
var obj = new constructorFn();

On printing obj, we now see

Object {value: "hello inner world"}
obj instanceof constructorFn

The result is FALSE.

when you start returning explicit, complex objects and arrays in a constructor function, you completely override the reference that is returned to the calling context.

Advertisements

One response to “Instance creation in Javascript

  1. Pingback: Instance creation part 2 | Using Abhik.Mitra.myThoughts;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s