0

I have an object called game in javascript. It creates another object called board. It then calls the move function in the board object. However, the board class uses animation. How do I send a callback function from the game object to the board object to be invoked by the board object?

I tried

    var game = new Game();
game.play()

function Game() {
    this.board = new Board();
    var callback = function () {
        this.doSomething();
        // put something here
    }
    this.play = function () {
        this.board.move(this.callback);
    }
}

function Board() {
    this.move = function (callback) {
        callback();
    }
}

But I get an error that this.doSomething is not defined.

Is there a way to call a function of another object from an object? Is there a way to call a function of a Game object in the Board object function?

1 Answer 1

1

You need to define this.board (while you have declared a Board constructor you actually haven't used it to create an object) for the Game object before you call it's play method. Similarly you also need to define callback

var game = new Game();
game.play()

function Game() {
    this.board = new Board();
    var callback = function () {
        // put something here
    }
    this.play = function () {
        this.board.move(callback);
    }
}

function Board() {
    this.move = function (callback) {
        callback();
    }
}

Responding to the comment in the thread below - if your callback function uses this you have to use bind (or call or apply)

Here's one way - note that you could bind to any object (not necessarily myVariable)

var myVariable = {
    myProperty: 10
}

var game = new Game();
game.play()

function Game() {
    this.board = new Board();
    var unboundCallback = function () {
        alert(this.myProperty)
    }
    var callback = unboundCallback.bind(myVariable)

    this.play = function () {
        this.board.move(callback);
    }
}

function Board() {
    this.move = function (callback) {
        callback();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I get an error because the callback function calls this. and its tells me this is not defined
What do you want this inside the callback function to be. Just use bind (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) or apply (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) or call.

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.