0

Why does my this.pPos is set to a string containing the function code, instead of the function return value?

http://jsfiddle.net/SpGwL/

function game(mode, boardDim) {
 //mod
 this.mode = mode;
 //dim tabla
 this.boardDim = boardDim;
 //pozitii initiale elemente
 if (this.mode == 'easy') {
 //creez pozitii specifice 
 this.pPos = function () {
 var pPos = Math.floor(Math.random() * Math.pow(this.boardDim, 2));
 return pPos;
 };
 }
}
var asd = new game('easy');
alert(asd.pPos);

This should return a random number, but it returns the function's text.

asked Jul 13, 2014 at 9:14
1
  • 1
    Because you're not calling the function, asd.pPos() Commented Jul 13, 2014 at 9:15

1 Answer 1

3

You have to call the function.

alert(asd.pPos());

Alerting the function itself will implicitly call toString() on it.

answered Jul 13, 2014 at 9:15
Sign up to request clarification or add additional context in comments.

2 Comments

+1, it's not text. It's just that Javascript gives you the function's code when you attempt to turn it into a string, like alert() does.
I need to wait 10 minutes.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.