2013-11-28 81 views
0

我正嘗試使用javascript創建一個小遊戲,並且一切都很順利,直到我必須開始一些東西時,我需要實例化一個「子彈」並將其開啓,但當調用「新的子彈()「我有一個」Uncaught TypeError:undefined不是一個函數「。 我如何實例化另一個對象方法內的對象?在javascript實例化方法中實例化一個對象

這是我做

function bullet(){ 
    //here it would be state for the bullet, like x and y and thigs 
    console.log("bullet created"); 
} 

function gun(){ 
    //state for the gun, amount of bullets and sort 
    console.log("gun created"); 

    this.fire = function(){ 
     //here we instantiate a bullet and fire it 
     console.log("begin fire"); 
     var bullet = new bullet(); 
     console.log("created bullet to fire"); 
    } 
} 

var gun = new gun(); 

gun.fire(); 
+1

將'var gun'和'var bullet'重命名爲其他內容... – Givi

回答

2

在JavaScript中的變量得到懸掛。要清楚這意味着什麼,編譯器將你寫的,如果你寫的代碼:

function gun(){ 
    //state for the gun, amount of bullets and sort 
    console.log("gun created"); 
    this.fire = function(){ 
     var bullet; 
     //here we instantiate a bullet and fire it 
     console.log("begin fire"); 
     bullet = new bullet(); 
     console.log("created bullet to fire"); 
    } 
} 

所以JS的所有變量聲明無法移動到當前功能範圍的頂部。請注意,這在所有編程語言中都不是這樣。在某些語言中,你可以用上面的方法獲得,bullet該變量將成功替換bullet的函數。

最好的解決方案是給你的變量一個不同的名字。

function gun(){ 
    //state for the gun, amount of bullets and sort 
    console.log("gun created"); 
    this.fire = function(){ 
     //here we instantiate a bullet and fire it 
     console.log("begin fire"); 
     var mybullet = new bullet(); 
     console.log("created bullet to fire"); 
    } 
} 

此外,由匈牙利提出來了,我想你是誤會了JS操作new

編輯:闡明瞭吊裝的含義。

+0

錯誤:子彈不是構造函數,但如果將var子彈更改爲子彈,那麼它的工作原理是http://jsfiddle.net/f962Y/ – Huangism

+0

是的,這也是一個問題,但這不是他遇到的問題。除了用new調用這個函數之外,只需將'this'設置爲一個對象的新實例,其構造函數指向該函數,但它仍然會「工作」。繼續嘗試。當你用新的函數調用一個函數時,JS不會崩潰和燒燬,它只是沒有做到你所期望的。 – Cyclone

+0

更新你的答案,所以它效果不錯 – Huangism

0

這是發生了什麼事。

當您撥打gun.fire();時,局部變量bullet被聲明並初始化爲'未定義',而表達式的其餘部分被評估。此表達式的求值查找名爲bullet的變量,並在局部範圍內找到它,忽略全局範圍中的子彈變量。

這教給我一些關於javascript的新東西,變量聲明不是原子的。

爲了解決這個問題,在Fire方法中重命名bullet變量,使其類似於firedBullet。