Moving from `prototype` and `new` to a closure-and-exposure pattern

前端 未结 4 1644
礼貌的吻别
礼貌的吻别 2021-01-21 14:07

I have been re-factoring someone else\'s JavaScript code.

BEFORE:

function SomeObj(flag) {
    var _private = true;
    this.flag = (fla         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 14:45

    Answers:

    1. You already answer this question: you loose the prototype chain. (Actually you don't loose it, but your prototype will be always empty). The consequences are:

      • There is a little performance/memory impact, because methods are created for each instance . But it depends a lot on the JavaScript engine, and you should worry about it only if you need to create a big amount of objects.

      • You can't monkey patch instances by modifying the prototype. Not a big issue either, since doing that leads to a maintenance nightmare.

    2. Let me do a small pedantic correction to your question: Is not a matter of "prototype vs closure", in fact the concept of closure is orthogonal to a prototype based language.

      The question is related on how you are going to create objects: define an new object from zero each time, or clone it from a prototype.

      The example that you show about using functions to limit the scope, is a usual practice in JavaScript, and you can continue doing that even if you decide to use prototypes. For example:

      var SomeObj = (function (flag) {
      
          /* all the stuff mentioned above, declared as 'private' `var`s */
      
          var MyObj = function() {}
          MyObj.prototype = {
              flag: flag,
              reset: reset
          };
      
          return {
             expose: function() { return new MyObj(); }
          }
      })();
      

      If you are worried about modularization, take a look into requirejs which is an implementation of a technique called AMD (async module definition). Some people doesn't like AMD and some people love it. My experience with it was positive: it helped me a lot to create a modular JavaScript app for the browser.

    3. There are some libraries to make your life with prototypes easier: composejs, dejavu, and my own barman (yes is a shameless self promotion, but you can look into the source code to see ways of dealing with definitions of objects).

      About patterns: Since you can easily hide object instantiation using factory methods, you can still use new to clone a prototype internally.

提交回复
热议问题