2016-07-23 91 views
0

問題:我試圖創建一個名爲嚮導一個構造函數有兩個參數:名稱和法術,然後創建一個嚮導對象:如何創建構造函數?

「嚮導的每個特定實例必須有一個name屬性(一字符串),一個是字符串數組的法術屬性和一個能夠以字符串格式返回隨機法術的castSpell方法。「

該對象具有以下屬性:name是「Gorrok」(字符串),spells是「abracadabra」和「cadabraabra」(數組)。

目的:調用castSpell方法來顯示一個隨機的法術,像這樣: Gorrok:胡言亂語

代碼:我只寫了下面的代碼,到目前爲止,我停留在這個階段!

function Wizard(name, spells){ 
    this.name = name; 
    this.spells = [spells]; 
    this.castSpell = function(){ 
     var v = Math.random(); 
     if (v >= 1) 
      document.write(this.name + " : " + this.spells[0]); 
     else 
      document.write(this.name + " : " + this.spells[1]); 
    } 
} 
var w = new Wizard("Gorrok", "abracadabra", "cadabraabra"); 
w.castSpell(); 

回答

2

所以,Math.random()將返回0和1之間的數字,所以它永遠不會大於1

而且,你不能將剩餘的參數轉換爲數組你有辦法。

簡單的解決辦法:

function Wizard(name, spells){ 
    this.name = name; 
    this.spells = spells; // assume spells is already an array 
    this.castSpell = function(){ 
     var v = Math.random(); 
     if (v >= 0.5) 
      document.write(this.name + " : " + this.spells[0]); 
     else 
      document.write(this.name + " : " + this.spells[1]); 
    } 
} 
var w = new Wizard("Gorrok", ["abracadabra", "cadabraabra"]); 
w.castSpell(); 
0

您還可以使用Math.round()得到0或1隨機

var v = Math.round(Math.random()); 
document.write(this.name + " : " + this.spells[v]); 
+0

洗牌的這種方式是新的給我,我喜歡你做了什麼沒有。究竟在哪種情況下你會使用Math.round(Math.random())?你可以在其中使用其他數學類嗎? – ratboy

+0

'Math.random'返回0到1之間的浮點數,'Math.round'將浮點數四捨五入到最接近的整數。當您使用Math。{someFunction}結果時,您不受限制。它可以像'var floatBetween0and1 = Math.random(); var number0or1 = Math.round(floatBetween0and1)' – Freez

1

我認爲保羅的答案是正確的。另外,對於不在ctor中的功能,請使用原型。原型還允許添加未在構造函數中定義的成員變量。

下面是一個例子,從W3:

function Person(first, last, age, eyecolor) { 
    this.firstName = first; 
    this.lastName = last; 
    this.age = age; 
    this.eyeColor = eyecolor; 
} 
Person.prototype.nationality = "English"; 
+0

值得指出的是,在大多數JavaScript運行時環境中,使用原型對內存分配有額外的好處。當在構造函數中定義一個函數時,它會爲該對象的每個實例分配一個新的函數實例,同時使用原型作爲該答案已完成的操作將只將該函數的一個副本分配給該類的所有實例。 – Paul

相關問題