2016-02-27 21 views
0

一切都在標題中......我知道使用原型創建的函數無法訪問私有對象數據/函數,但是如何訪問在創建時傳遞給對象的參數呢?JS原型是否可以訪問在初始化期間傳遞給對象的參數?

var Voice = function (word) 
{ 
    /* 
     I know I can obviously do something like : 'this.word = word;' 
     But I was wondering whether there is a standard way of calling an 
     argument from within a prototype function without having to do 
     the above ? 
    */ 
}; 

Voice.prototype.speak = function() 
{ 
    console.log({{word}}); 
}; 

x = new Voice('all I can say is this'); 
x.speak(); 

謝謝!

回答

3

對樣機的功能號並沒有這兩個變量的範圍爲函數中定義的,所以它們沒有訪問它們。

您可以將變量作爲對象屬性存儲,然後從那裏讀取它。

this.word = word; 
+0

哎呀。我正在更新我的職務,而你發佈你的答案.. :-)不夠公平。這回答我的問題, 謝謝! –

+0

如果他們允許像'Voice.prototype.speak = function(){this.arguments.word}'這樣的話,它會很酷,其中'arguments'顯然是一個保留的詞,對吧?無論如何..再次感謝。 –

-1

也許是這樣的:

var Voice = function (word) { 
 
    this.init_word = word; 
 
}; 
 

 
Voice.prototype.speak = function(){ 
 
    console.log(this.init_word); 
 
}; 
 

 
x = new Voice('all I can say is this'); 
 
x.speak();

相關問題