Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  43] [ 7]  / answers: 1 / hits: 63212  / 13 Years ago, sat, march 10, 2012, 12:00:00

I have a question concerning how the this pointer is treated in a nested function scenario.



Say I insert this following sample code into a web page. I get an error when I call the nested function doSomeEffects(). I checked in Firebug and it indicates that when I am in that nested function, the this pointer is actually pointing to the global window object - which I did not expect. I must not be understanding something correctly because I thought since I declared the nested function within a function of the object, it should have local scope in relation to the function (i.e. the this pointer would be referring to the object itself like how it is in my first if statement).



Any pointers (no pun intended) would be appreciated.



var std_obj = {
options : { rows: 0, cols: 0 },
activeEffect : none,
displayMe : function() {

// the 'this' pointer is referring to the std_obj
if (this.activeEffect==fade) { }

var doSomeEffects = function() {

// the 'this' pointer is referring to the window obj, why?
if (this.activeEffect==fade) { }

}

doSomeEffects();
}
};

std_obj.displayMe();

More From » function

 Answers
15

In JavaScript the this object is really based on how you make your function calls.



In general there are three ways to setup the this object:




  1. someThing.someFunction(arg1, arg2, argN)

  2. someFunction.call(someThing, arg1, arg2, argN)

  3. someFunction.apply(someThing, [arg1, arg2, argN])



In all of the above examples the this object will be someThing.
Calling a function without a leading parent object will generally get you the global object which in most browsers means the window object.


[#86938] Thursday, March 8, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aliah

Total Points: 118
Total Questions: 132
Total Answers: 94

Location: Tajikistan
Member since Fri, Sep 11, 2020
4 Years ago
;