Sunday, March 27, 2011

Function object and this in javascript

Unlike other languages, function in javascript is an object same as other instance object. For example, if the following function is defined
function f(m,n) {
this.x = m;
this.y = n;
}

Then calling
var o1 = f;
Then the type of o is an object that represents the function. It is not a instance that is created by the f function.

Now let us see what happens if calling
var o2 = new f;
This time, the function serves as the construct to create a instance . The instance has two data member x, and y, whose values are not initialized. To set the data member values, calling
var o3 = new f(1, 2);

Now try to use the function in a different way as showing below
var o3 = f(2, 3);
This time, the function f is not used as a constructor, instead it is just a normal javascript method call, inside the function f, this pointer points to the window object of the current html page, and it just sets two new data members to the window object.

Another thing unique in javascript is, although any object instance can add new data members by just calling assigning operation as below
this.x = somevalue;

It can not do so to directly call a javascript funtion on an instance object. Instead, it must first assign the function to the instance's member before calling the function on it.
this.f = somefunction;
this.f();

By the way, the this point in javascript function call chain is not inherited. So if within a function A, the this points to instance Obj1, then calling function b from function A, within the function b, the this pointer is the global object, instead of Obj1. If you want to set the this pointer Obj1 to be function b's this pointer, then you must first assign function b as a member of Obj1, and then calling function as its member function. This also explains why we need to assign onclick attribute to a external function and then call onclick to keep the current html element as the external function's this object.

No comments:

Post a Comment