Search code examples
javascriptmethodsprivate

Add private method in JavaScript?


I'm trying to make a basic game to strengthen my JavaScript knowledge. But I need some help with trying to add private methods to an object. The reason for this is that I want to the user to be able to access certain moves once they reach a certain condition, but not before. I also don't want to have to add the methods each time the character levels up. Here is some code:

function Character(name, type, sex) {
    this.name = name;
    this.type = type;
    this.sex = sex;
    //Ignore this part as well this.punch = function() {
        //Ignore this. Will work on later
    }
};

var rock = new Character('Stoner', 'Rock', 'Male');

Solution

  • I don't think this is what the OP is looking for... It seems like the OP wants them "private" until the user hits a certain level and then public

    Assuming this comment is right...

    It doesn't need to be a private method, have it be a public method and then use an if/else statement to handle if they don't have enough "levels".

    function Character(name, type, sex) {
      this.name = name;
      this.type = type;
      this.sex = sex;
    
      this.level = 10;
    
      this.punch = (function(){
        if (this.level > 5) {
          /* Punch functionality goes here. */
        } else {
          /* They don't have enough levels, tell them that! */
        }
      }).bind(this)
    }
    

    I'm only assuming you're using levels. If you have some other system, you can simply adapt it.