JavaScript private methods

前端 未结 30 2083
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:16

To make a JavaScript class with a public method I\'d do something like:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something         


        
30条回答
  •  鱼传尺愫
    2020-11-22 08:59

    The module pattern is right in most cases. But if you have thousands of instances, classes save memory. If saving memory is a concern and your objects contain a small amount of private data, but have a lot of public functions, then you'll want all public functions to live in the .prototype to save memory.

    This is what I came up with:

    var MyClass = (function () {
        var secret = {}; // You can only getPriv() if you know this
        function MyClass() {
            var that = this, priv = {
                foo: 0 // ... and other private values
            };
            that.getPriv = function (proof) {
                return (proof === secret) && priv;
            };
        }
        MyClass.prototype.inc = function () {
            var priv = this.getPriv(secret);
            priv.foo += 1;
            return priv.foo;
        };
        return MyClass;
    }());
    var x = new MyClass();
    x.inc(); // 1
    x.inc(); // 2
    

    The object priv contains private properties. It is accessible through the public function getPriv(), but this function returns false unless you pass it the secret, and this is only known inside the main closure.

提交回复
热议问题