Search code examples
javascriptencapsulation

js add encapsulation to modify property value


I have this class:

function level(intLevel) {
    this.identifier = 'level';
    this.intLevel = intLevel;
    this.strLocation = 'Unknown';
    displayLocation : function(locationName){
        this.strLocation = locationName;
    };
    this.monsterDelay = 300;
    this.setGrid(50, 24);
    return this;
}

and I am trying to add e method to update the strLocation.

I would than call:

displayLocation('location');

Is this correct?


Solution

  • displayLocation method is a function and just one more property. Property can be anything: primitive type, object or function. So you should configure it the same as you did with other properties:

    this.displayLocation = function(locationName){
        this.strLocation = locationName;
    };
    

    Another improvement, is that you might want to move reusable method to the function prototype so it's not recreated on every instance instantiation:

    function level(intLevel) {
        this.identifier = 'level';
        this.intLevel = intLevel;
        this.strLocation = 'Unknown';
        this.monsterDelay = 300;
        this.setGrid(50, 24);
    }
    
    level.prototype.displayLocation = function(locationName) {
        this.strLocation = locationName;
    };
    

    Couple of notes. You don't need to return this, as return this is implied automatically. It is also recommended to name constructor functions with capital letter, in your case Level would look better.