JavaScript private methods

前端 未结 30 1856
-上瘾入骨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:57

    I prefer to store private data in an associated WeakMap. This allows you to keep your public methods on the prototype where they belong. This seems to be the most efficient way to handle this problem for large numbers of objects.

    const data = new WeakMap();
    
    function Foo(value) {
        data.set(this, {value});
    }
    
    // public method accessing private value
    Foo.prototype.accessValue = function() {
        return data.get(this).value;
    }
    
    // private 'method' accessing private value
    function accessValue(foo) {
        return data.get(foo).value;
    }
    
    export {Foo};
    

提交回复
热议问题