我試圖通過使用我定義的特權方法更改私有成員。我創建了一個簡單的類來給你我有當前問題的例子:使用私有參數作爲輸入訪問私有方法的Javascript OOP特權方法
// Constructor
function Player(name) {
// Private
var achievements = [];
function emptyArray(emptyThisArray) {
emptyThisArray = [];
};
// Privileged
this.restartGame = function() {
this.score = 0;
emptyArray(achievements);
};
this.addAchievement = function() {
achievements[achievements.length] = "Medal " + achievements.length;
};
this.getAchievements = function() {
return achievements;
};
// Public
this.name = name;
this.score = 0;
}
// Public
Player.prototype.getName = function() {
return this.name;
};
var player1 = new Player("Ben");
player1.score = 100;
player1.addAchievement();
player1.addAchievement();
player1.getAchievements();
player1.restartGame(); // restart the game
player1.score; // returns 0
player1.getAchievements(); // return an array of two achievements: ["Medal 0", "Medal 1"] (should actually return an empty array)
當我嘗試執行特權方法restartGame將比分正確地設置爲零。但是,當我嘗試清除私有數組(在這個例子中的成就)。專用陣列沒有被清除。什麼是正確的方法來做到這一點?
我被標記了正確的答案,但這是正確的,並在我回答之前發佈了一分鐘。 +1 – 2011-04-20 21:20:45