1
function Test(){
    this.update = function(entity){
              entity.forEach(function(enemy) {
                    this.checkHit(enemy);
                });
        }

        this.checkHit = function(entity){
                console.log("worked!");
        }

}

How can I call Test's this.checkHit function, and pass it the current value in the entity's foreach loop?

Current code gives "this.checkHit" is not a function.

2
  • 4
    var that = this; .......... Commented Feb 7, 2014 at 10:16
  • check console.log(this) and do changes as suggested by @zerkms Commented Feb 7, 2014 at 10:19

2 Answers 2

3

If you don't care about old browsers - which seems to be the case since you're using forEach - you could use bind (also I assume that you're doing new Test() somewhere) :

entity.forEach(function (enemy) {
    this.checkHit(enemy);
}.bind(this));
Sign up to request clarification or add additional context in comments.

Comments

0

Just put this in a normal variable. self is commonly used

function Test(){
    var self = this;
    this.update = function(entity){
              entity.forEach(function(enemy) {
                    self.checkHit(enemy);
                });
        }

        this.checkHit = function(entity){
                console.log("worked!");
        }

}

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.