Uncaught typeerror: Object # <object> does not have a method 'method'

So here is the object 'playerTurnObj'

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

and that's what i do with it

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

so I am trying to make the script method setTurn () in playerTurnObj () in order to keep the β€œrotation” in the game that I am doing. The problem is that it does not turn.setTurn (1); because i keep getting the error above

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

+4
source share
3 answers

This is not how JavaScript works. Your constructor function contains built-in functions that are not visible outside the playerTurnObj . Thus, your turn variable does not have a specific setTurn method since the error message is correct. You probably 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; } }; 

Your turn variable now has two setTurn and getTurn that work with an instance created with new .

+1
source

The setTurn and getTurn are private, so they return undefined instead of calling 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; } } 

Then you have the public setTurn and getTurn and you can call them like this:

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

http://jsfiddle.net/Ht688/

+1
source

What I'm doing from this, you need to return the object to the playerTurnObj () function. So your new code will look something like this:

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

Source: https://habr.com/ru/post/1481518/


All Articles