Understanding public/private instance variables

前端 未结 2 640
耶瑟儿~
耶瑟儿~ 2021-01-25 09:14

I am reading a tutorial on public/private methods and can\'t make sense of the difference.

For a private method it says, \"Private members are made by the constructor. O

2条回答
  •  难免孤独
    2021-01-25 09:47

    No one of this variable is trully private because if you instanciate Container you can access to secret variable :

    function Container(param) {
        this.member = param;
        var secret = 3;
        var that = this;
    }
    
    var container = new Container();
    console.log(container.secret);
    container.secret = "toto";
    console.log(container.secret);
    console.log(container);
    

    Here the result :

    As you can see you can access to secret without any "Getter/Setter".

    If you want to do object javascript with truly private variable, look at this tutorial :

    http://blog.stchur.com/2011/09/26/true-private-variables-in-javascript-with-prototype/

提交回复
热议问题