1

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 object itself... I have no idea why. Can someone explain what is happening here?

function Feed_Item(data) {
  this.data = data;
  this.get_data = function() {
    return this.data;
  }

  this.foo = function() {
    return this.foo2();
  }
  this.foo2 = function() {
    //here type of this.data() == Feed_Item!!! It should be of type Data
  }
  this.bar = function() {
    //here type of this.data() == Data, as I'd expect
  }
}
will
  • 3,103
  • 4
  • 25
  • 30
  • 7
    You'd have to show us the code where you invoke the methods - since `this` is invocation dependent it might have an influence. Also, what's `this.data()`? You don't have a function named `data`, aside from the `data` parameter. Is `data` a function? – ZenMaster Oct 31 '11 at 06:35
  • The value of a function's this keyword depends entirely on how it is called. Read the answers to ['this' keyword, not clear](http://stackoverflow.com/questions/5429739/this-keyword-not-clear). – RobG Oct 31 '11 at 06:38
  • 1
    do you really need `this.get_data()`? Can't you just call `this.data`? It seems like something you would do in Java/C++ where some attributes are private. – puk Oct 31 '11 at 06:55

2 Answers2

1

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/

Kosta
  • 812
  • 1
  • 7
  • 13
0

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.

Mark Rhodes
  • 10,049
  • 4
  • 48
  • 51