2014-07-13 68 views
0

爲什麼我的this.pPos被設置爲包含函數代碼的字符串,而不是函數返回值?Javascript變量設置爲字符串

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); 

這將返回一個隨機數,但它返回函數的文本。

+1

因爲你沒有調用這個函數,'asd.pPos()' – elclanrs

回答

3

你必須請致電的功能。

alert(asd.pPos()); 

提醒函數本身會隱式地調用toString()

+0

我很愚蠢。謝謝。 –

+0

+1,這不是文字。只是當你試圖把它變成一個字符串時,Javascript會給你函數的代碼,就像'alert()'一樣。 – slezica

+0

@喬治將它標記爲已接受,請問.. – nsthethunderbolt