2014-12-05 40 views
0

我是JavaScript中創建對象的新手。我需要製作一個不會經常重複的隨機數字生成器(我沒有嘗試在下面的代碼片段中實現該部分)。如何在RNG.prototype.rand中從函數RNG(n)訪問n?它在我的編輯器中以我現在寫的方式顯示爲無法訪問。我也不能確定我是否應該從RNGRNG...rand()返回:JavaScript中的自定義隨機數生成器

function RNG(n) { 
    this.n = n; 
} 

RNG.prototype.rand = function() { 
    var arr = []; 
    var num = Math.floor(Math.rand()*n); 

    //keep array of generated numbers 
    if(num < arr[0]){ 
    arr.unshift(num); 
    } 
    else{ 
    arr.push(num); 
    } 
} 
+0

['.n'是一個屬性,但你使用它像一個變量(HTTP ://stackoverflow.com/q/13418669/1048572) – Bergi 2014-12-05 05:55:28

回答

2

this.n是創建一個實例屬性當實例實例:

function RNG(n) { 
    this.n = n; 
} 

var rng = new RNG(5); 
console.log(rng.n); // 5 

RNG.prototype.rand是一個實例方法。在該方法中,如果你想引用實例本身,你也應該使用this

function RNG(n) { 
    this.n = n; 
} 
RNG.prototype.method = function() { 
    console.log(this.n); 
}; 

var rng = new RNG(7); 
rng.method(); // 7, within this method `this` is `rng`, so `this.n` gives you `rng.n` 

如果你試試這個代碼:

function RNG(n) { 
    this.n = n; 
} 
RNG.prototype.method = function() { 
    var n = 3; 
    console.log(n, this.n); 
}; 

var rng = new RNG(7); 
rng.method(); // 3, 7 

這裏沒有this.n實際上是試圖獲得與var n = 3;定義的變量。它無關的實例屬性rng.n

最後,如果你沒有定義n

function RNG(n) { 
    this.n = n; 
} 
RNG.prototype.method = function() { 
    console.log(n); 
}; 

var rng = new RNG(7); 
rng.method(); // ReferenceError: n is not defined 
3

在你的代碼要this.n而非n。與某些語言不同,「這個」不是假定的。

爲了回答您的其他問題,您可以將它設置在這裏的樣子,你想從rand返回,但坦率地說,我不看製作的,爲什麼你不只是把n作爲一個參數去rand()代替一個有狀態的對象w /一個構造函數和什麼。

+0

我正在對代碼大戰進行練習,這就是它如何給出的。如果你能想到這種方法可能產生的任何好處,我會很高興聽到他們的聲音。 Jscript中的「this」與Java中的相同嗎? – user137717 2014-12-05 05:41:52

+0

通常,如果您想要在多個函數中共享更多數據,則可以使用此模式。 'this'與Java版本類似,但我不會說它的工作原理完全一樣,不。 – Paul 2014-12-05 06:06:48