0

I want to build a class using javascript like in c, the main problem is private attribute.

var tree = {
  private_var: 5,
  getPrivate:function(){
   return this.private_var;
  }
};
console.log(tree.private_var);//5 this line want to return unaccessible
console.log(tree.getPrivate());//5

so I want to detect the access from tree.private_var and return unaccessible, and this.private_var return 5.
My question is: Is there any way to set private attribute in javascript?

EDIT: I saw this way

class Countdown {
    constructor(counter, action) {
        this._counter = counter;
        this._action = action;
    }
    dec() {
        if (this._counter < 1) return;
        this._counter--;
        if (this._counter === 0) {
            this._action();
        }
    }
}
CountDown a;

a._counter is not accessible? but

Barmar
  • 741,623
  • 53
  • 500
  • 612
My Favorite Bear
  • 114
  • 1
  • 1
  • 10

1 Answers1

1

Define tree as a function instead of JavaScript object, define private variable in the function by var keyword, define public getting function by this. keyword and create a new instance by using the function

var Tree = function(){
    var private_var = 5;
    this.getPrivate = function(){
        return private_var;
    }
}

var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5

In ES6, you can do this but it is not supported by IE so I wouldn't recommend

class Tree{
    constructor(){
        var private_var =5;
        this.getPrivate = function(){ return private_var }

    }
}

var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5
Solomon Tam
  • 739
  • 3
  • 11