0

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!

2 Answers 2

1

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;

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.