Closures vs. classes for encapsulation?

前端 未结 3 1043
我在风中等你
我在风中等你 2021-02-02 10:10

I\'m new to JS (from C++/etc), and it\'s just occurred to me that closures seem to be a simpler and more convenient way to handle encapsulation than classes. This code seems to

3条回答
  •  我在风中等你
    2021-02-02 10:22

    The reasons to avoid closures is overhead.

    Your get and set functions are trivially 20x slower than properties. Your closures also have a large memory overhead that is O(N) with the number of instances.

    Also note that these encapsulated variables have zero real benefit, they just infer performance penalties.

    var AddProperty = {
      constructor: function (v) { this._value = v; return this; },
      get: function () { return this._value; },
      set: function (v) { this._value = v; }
    };
    
    var a = Object.create(AddProperty).constructor(1);
    var b = Object.create(AddProperty).constructor(2);
    

    I noticed yesterday that this doesn't work, because my JS code doesn't keep any private state for each tab.

    Your problem is not that you don't have private state, it's that you're using global state.

    The easy solution is to have an object per tab (or a "struct" if you prefer) and store state in it.

    So all you have to do is define a tab

    var Tab = {
      constructor: function (...) {
        /* init state */
      },
      doTabStuff: function () { /* some method */ },
      ...
    }
    

    And then create new tabs when you need them

    var tab = Object.create(Tab).constructor(...)
    

提交回复
热议问题