Sunday, March 21, 2010

Object Oriented JavaScript Part2 -- "this"

People experienced with some Object Oriented Programming language like Java and Python must be very familiar with using "this" pointer. JavaScript also involves a lot of uses with the "this" pointer.

The first question that we usually need to solve is that "Where does the 'this' pointer exist?". This is a rather simple question with JavaScript. The "this" pointer exists within any "Function" object ( As some of people already know that "function" is an instance of the global "Object" object in JavaScript; therefore, we will usually say the "Function" object. ). Code below will exhibit how a function is declared in JavaScript:


function myFunction(arg1) {
console.log(arg1);
}

These lines of code simply declares a Function object and one can simply just add a line like this this.name = "myName"; within this function. As we can see, "this" pointer exists within the function definition


I guess the most confusing part is to figure out what the "this" pointer points to? A rule of thumb to define what the "this" points to is that " 'this' pointer points to the object that contains the function where the 'this' exists within ". Within the code above 'this' pointer points to the 'window' object if that function is declared in the web page globally

No comments:

Post a Comment