I\'m having a confusing problem using \'this\' in javascript. I have a method \'get_data\' which returns me some member variable of an object. Sometimes it returns to me the o
A good blog post that explains "this" is available here: http://www.scottlogic.co.uk/2010/05/what-is-this/
Essentially the definition of this
is:
The value of this is determined at the point at which the function is invoked, and is set to the object on which the function is invoked
However sometimes it's not easy to figure out exactly what that object is. This is because it depends on how the function is invoked. You can even dynamically set the value of this by invoking the function via its call
method e.g.
window.str = "hello";
var fn = function(){
alert(this.str);
};
fn();
Running this code in the browser console gives hello
which is the value of str
on the global window
object, however if you run:
fn.call({
str: 'goodbye'
}, []);
You get 'goodbye', as the context has been changed to the object passed in. Some libraries e.g. JQuery, ExtJS, ... make use of this feature to make then easier to use.