Typeerror not intercepted: Object # & lt; object & gt; does not have a method 'method'

advertisements

So here's the object 'playerTurnObj'

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
    function setTurn(turnToSet) {
        this.playerTurn=turnToSet;
    }
    function getTurn() {
        return this.playerTurn;
    }
}

and here is what I'm doing with it

var turn = new playerTurnObj();
turn.setTurn(1);

so I try to make the script do the setTurn() method in playerTurnObj() to save a 'turn' in a game I'm making. The problem is, it does not do the turn.setTurn(1); part because I keep getting the error above

what am I doing wrong? I searched, but I could not find an exact answer to my question.


This is not the way JavaScript works. Your "constructor" function contains inline functions that are not visible outside of the scope of playerTurnObj. So your variable turn does not have a method setTurn defined, as the error message states correctly. Probably you want something like this:

function playerTurnObj(set_turn) {
    this.playerTurn=set_turn;
}

playerTurnObj.prototype = {
    setTurn: function(turnToSet) {
        this.playerTurn=turnToSet;
    },
    getTurn: function() {
        return this.playerTurn;
    }
};

Now your variable turn has two methods setTurn and getTurn that operate on the instance you created with new.