4

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.

3 Answers 3

1

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.

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

1 Comment

The other suggestions here do work too, there are many ways to achieve this. Usind prototype has the advantage of not filling up memory with each instance.
1

The setTurn and getTurn functions are private so they return undefined rather than invoking the function. You can do:

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

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

You then have public setTurn and getTurn methods and can invoke them as follows:

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

http://jsfiddle.net/Ht688/

Comments

0

What I make out of it is you need to return the object this in function playerTurnObj(). So your new code will look something like:

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

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.