0

Hi I have the following code where I am calling a function that takes a callback function that takes a parameter. Basically I am trying to get the contents of e into this.items but I cant escape the callback function?

function stash(){
    this.items = new Array();

    this.get = function(){
      opr.stash.query({},function(e){
         console.log(this.items); //this is not defined
      });
    }
}

s = new stash();
s.get();
user550
  • 328
  • 1
  • 5
  • 11
  • possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Felix Kling Mar 29 '14 at 20:00

3 Answers3

2

Problem: callback function's context object (this) no longer refers to the context object of get() method.

Solution: bind your callback function to the target object, like this:

opr.stash.query({},(function(e){
  console.log(this.items);
}).bind(this));
raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

this is no longer in scope on the callback so make a reference to it that you can user later. The .bind(this) is a good solution in modern browsers but may fail in older versions of Internet Explorer as that method may not be available.

function stash(){
        var self = this; 
        this.items = new Array();

        this.get = function(){
          opr.stash.query({},function(e){
             console.log(self.items); 
          });
        }
    }
Alex Wolfe
  • 39
  • 5
0

I ran into a similar problem in d3.chart.

I don't have access to opr.stash at the moment so i couldn't test this first, but have you tried something like the following:

function stash()
{
    var myStash = this;

    myStash.items = new Array();

    myStash.get = function(){
       opr.stash.query({},function(e){
       console.log(myStash.items); //this is not defined
      });
    }
}

s = new stash();
s.get();
Christopher
  • 1,327
  • 10
  • 17