Wednesday, December 7, 2011

Javascript Functions

JavaScript Functions -- Inferences

  1. Functions are fundamental modular units.
  2. Functions are Objects
  3. Every object has object.protoype property which is used for inheritance.
  4. Functions also have a Prototype property that is internally connected to Object.prototype.
  5. Function .prototype is a constructor property whose value is the function itself.
  6.  Since they are objects they can be passed as objects.
  7. When a function is invoked with .(Dot) or [Subscript] then the function becomes a method. 
  8. The Function by default gets "arguments" as default argument even if it is not present in function signature however it is not exactly an array object but has "length" property.
  9. This Keyword
    • If a function is defined within an Object and when function is invoked with that object."This" is tied to object. 
    • Any Object is used to invoke function accessing "This" will retrive that objectinside function scope.
    • When we use Nested Functions "This" will always refer to global object so the nested function cannot access the variables of the outer function.This is actually a defect of javascript whenever a nested function is invoked java script loses the scope and so it binds "This" to window object.However there are ways to retrieve outer function properties
       Eg :  
    • MyObject.double=function()
                  {

                     var that =this; // if this assignment copies the this object to the variable and makes it 
                           //avaliable for nested functions.
                     var helper=function()
                         {
                      that.value=add(that.value,1); //
                       alert(this);// will print window object
                         }
                       helper();
                     }
         
    • MyObject.double=function()
                  {
                     var that =this; // if this assignment copies the this object to the variable and makes it 
                           //avaliable for nested functions.
                     var helper=function()
                         {
                      that.value=add(that.value,1); //
                       alert(this);// will print window object
                         }
                     this.call(helper,' '); // Use apply or call here and the "This Object" 
                                                   //will be visible inside with proper scope.
                     }



No comments:

Post a Comment