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.
What 'this' is in JavaScript depends on how you call the function. If 'this' is not bound to an object, this will be the window object.
If you call
item = new Feed_Item()
item.foo() //foo will be called with correct 'this'
But if you do Feed_Item(some_data), you will add a couple of functions to the global window object.
There are a lot of articles explaining this, e.g. http://www.digital-web.com/articles/scope_in_javascript/