I'm trying to change a private member by using a Privileged method that I defined. I created a simple class to give you an example of the current issue I'm having:
// 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)
When I try to execute the Privileged method restartGame the score will be correctly set to zero. But when I try to clear the private array (in this example achievements). The private array is not getting cleared. What is the correct way to do this?
Your emptyArray
function should just be
function emptyArray(array) {
array.length = 0;
};
or even better ...
function emptyArray() {
achievements = [];
};
The way you have it now, you are setting a pointer to the achievements array to point to a new array, leaving the original array intact. Passing an array to a function creates another reference to the array, not a reference to the original variable.
You have emptyArray()
as this:
function emptyArray(emptyThisArray) {
emptyThisArray = [];
};
That just sets the emptyThisArray
variable to a new array and leaves the passed-in array unchanged. It should be this:
function emptyArray() {
achievements = [];
};
精彩评论