user687554
user687554

Reputation: 11131

Passing JavaScript to Closure in JavaScript

I'm learning how to actually use JavaScript. I've run into a situation where I'm getting an error. The error is: TypeError: 'undefined' is not an object (evaluating 'this.flagged'). I've narrowed down my code to where its happening. My code looks like this:

var flagged = false;
var intervals = [];

return {
  flagged: flagged,
  intervals: intervals,

  createInterval : function (options) {
    var defer = $q.defer();
    if (this.throwsError) {
      defer.reject('There was an error creating the interval.');
    } else {
      this.intervals.push(
        $interval(function() {
          console.log('here 1');
          console.log(this.flagged); 
        },
        1000
      ));
    }
  }
};

The error gets thrown at the: console.log(this.flagged); I'm guessing it has to do with the fact that "this" isn't visible. Yet, if "this" isn't visible, I'm not sure how to get the value for flagged. Can someone please explain to me what I need to do to get the value for flagged?

Thank you!

Upvotes: 0

Views: 58

Answers (2)

Abdul Jabbar
Abdul Jabbar

Reputation: 2573

In JavaScript,

var flagged

will be a scoped variable, i think what you need here is a global scope variable for that, simply remove var from behind it.

flagged = false;

that should do the trick.

Upvotes: 0

domakas
domakas

Reputation: 1246

When you are using this inside $interval it won't be pointing to your original object, however, you can do this:

var flagged = false;
var intervals = [];

return {
  flagged: flagged,
  intervals: intervals,

  createInterval : function (options) {
    var defer = $q.defer(),
        self = this;
    if (this.throwsError) {
      defer.reject('There was an error creating the interval.');
    } else {
      this.intervals.push(
        $interval(function() {
          console.log('here 1');
          console.log(self.flagged); 
        },
        1000
      ));
    }
  }
};

notice var self = this;

Upvotes: 1

Related Questions