2015-02-17 46 views
-1

我想修改getSecret函數以使私有變量'secret'可以從'bestfriends'類之外訪問。修改函數以訪問類之外的私有變量

任何想法?

function bestfriends(name1, name2) { 
this.friend1 = name1; 
this.friend2 = name2; 
var secret = "Hakuna Matata!"; 
console.log (this.friend1 + ' and ' + this.friend2 + ' are the best of friends! '); 
} 

bestfriends.prototype.getSecret = function() { 
    return secret 
} 

var timon_pubmaa = bestfriends('timon', 'pumbaa'); 

var timon_pumbaa_secret = getSecret(); 

console.log(timon_pumbaa_secret); 
+1

1.'變種timon_pubmaa =新bestfriends( '蒂莫', '彭彭');''2.變種timon_pumbaa_secret = timon_pubmaa.getSecret();''3.返回this.secret' 4.'此.secret = ...'或者在構造函數中移動getSecret'實現並使用閉包。 – zerkms 2015-02-17 20:27:20

+0

你不能。您可以將該屬性設爲公共或公開屬性,也可以從相同範圍公開該屬性,但不能修改對私有屬性範圍的訪問權限。 – Mathletics 2015-02-17 23:44:44

回答

0

您忘記使用new關鍵字bestfriends

getSecret應該在​​這樣的實例上調用。

您的secret變量是構造函數的本地變量,它不能從該方法訪問。爲了達到這個目的,你可以創建一個閉包並返回你的構造函數,並且在閉包中你可以創建一些私有的變量。

var bestfriends = (function() { 

    var secret; // private variable 

    function bestfriends(name1, name2) { 
     this.friend1 = name1; 
     this.friend2 = name2; 
     secret = "Hakuna Matata!"; 
     console.log(this.friend1 + ' and ' + this.friend2 + ' are the best of friends! '); 
    } 

    bestfriends.prototype.getSecret = function() { 
     return secret 
    } 

    return bestfriends; 

})(); 

var timon_pubmaa = new bestfriends('timon', 'pumbaa'); 
var timon_pumbaa_secret = timon_pubmaa.getSecret(); 
console.log(timon_pumbaa_secret); // Hakuna Matata! 
+0

當我輸入上面的代碼時,我得到「ReferenceError:getSecret沒有定義」 – mdarmanin 2015-02-17 20:39:15

+0

如果'secret'變量是靜態的(可以被整個類訪問),你不應該從構造函數初始化它。 – Bergi 2015-02-17 21:04:25

+0

我已經走了並在代碼頂部添加了祕密變量,但我仍然得到相同的結果:「ReferenceError:getSecret未定義」 – mdarmanin 2015-02-17 21:20:39