Pseudo-classical vs. “The JavaScript way”

后端 未结 4 711
野趣味
野趣味 2021-01-30 03:22

Just finished reading Crockford\'s \"JavaScript: The Good Parts\" and I have a question concerning his stance on the psuedo-classical vs. prototypal approaches.

4条回答
  •  梦如初夏
    2021-01-30 04:03

    The prototypal variant for the example you have looks like the following in my understanding:

    Object.beget = function (o) { /* Crockfords replacement for the new */ }
    
    var myModule = {
        something : null,
        getSomething : function () {},
        setSomething : function () {},
        doSomething : function () {}
    };
    

    And then you can do:

    var foo = Object.beget(myModule);
    foo.something = bar;
    

    UPDATE: You can also use the builder pattern to replace a constructor like this:

    var myModuleBuilder = {
        buildMyModule : function (something) {
            var m = Object.beget(myModule);
            m.something = something || {};
            return m;
        }
    }
    

    so then you can do:

    var foo = myModuleBuilder.buildMyModule(something);
    

提交回复
热议问题