Sunday, 23 June 2013

JavaScript function / protoype variables and their behavior

Sunday, 23 June 2013
I was trying out some JavaScript and suddenly surprised by awkward behavior of some function variables. Functions in JavaScript are first class citizens and are very confusing especially for OOP programmers. They always confused me too. So this time I did not took any chance and tried out some code to determine how exactly the variables defined in function behave.

I realized that we can define variables in function in many different ways:
  1. as this.variableName inside function definition
  2. as var variableName inside function definition
  3. as functionName.prototype.variableName outside function definition
  4. as functionName.variableName outside function definition
I have put the code in the below JSFiddle and explained it in the comments. Hope this helps you.
Note: The JSFiddle may not work completely on all browsers. Better view it on Chrome or Opera.