Mike
Mike

Reputation: 23

Javascript OOP privilege method accessing private method with private parameter as input

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?

Upvotes: 2

Views: 164

Answers (2)

Mark Cidade
Mark Cidade

Reputation: 100007

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 = [];
};

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92314

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.

Upvotes: 2

Related Questions