Kyle Simpson's OLOO Pattern vs Prototype Design Pattern

前端 未结 8 1620
终归单人心
终归单人心 2020-12-02 03:41

Does Kyle Simpson\'s \"OLOO (Objects Linking to Other Objects) Pattern\" differ in any way from the the Prototype design pattern? Other than coining it by something that spe

8条回答
  •  抹茶落季
    2020-12-02 04:24

    @Marcus, just like you, I have been keen on OLOO and also dislike the asymmetry as described in your first point. I've been playing with an abstraction to bring the symmetry back. You could create a link() function that is used in place of Object.create(). When used, your code could look something like this...

    var Point = {
        init  : function(x,y) {
            this.x = x;
            this.y = y;
        }
    };
    
    
    var Point3D = link(Point, {
        init: function(x,y,z) {
            Point.init.call(this, x, y);
            this.z = z;
        }
    });
    

    Remember that Object.create() has a second parameter that can be passed in. Here is the link function that leverages the second parameter. It also allows a little bit of custom configuration...

    function link(delegate, props, propsConfig) {
      props = props || {};
      propsConfig = propsConfig || {};
    
      var obj = {};
      Object.keys(props).forEach(function (key) {
        obj[key] = {
          value: props[key],
          enumerable: propsConfig.isEnumerable || true,
          writable: propsConfig.isWritable || true,
          configurable: propsConfig.isConfigurable || true
        };
      });
    
      return Object.create(delegate, obj);
    }
    

    Of course, I think @Kyle would not endorse shadowing the init() function in the Point3D object. ;-)

提交回复
热议问题