How to write JavaScript with factory functions

前端 未结 6 1309
野趣味
野趣味 2021-01-01 00:55

I\'m reading this article about perils of trying to mimic OOP in JavaScript and there\'s the following:

In JavaScript, factory functions are simply co

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 01:25

    No, that is wrong. You should not use Object.setPrototypeOf, better use Object.create (though it makes no difference for the result). And if you create the prototype from an object literal every time, it loses all of its sharing advantages, so you should either drop that completely or move it outside the function to make it static. The correct™ way to write the factory function would be

    const protoRabbit = {
        getSpeed: function() {
            return this.speed;
        }
    };
    function createRabbit() {
        var rabbit = Object.create(protoRabbit);
        rabbit.speed = 3;
        return rabbit;
    }
    
    var rabbit = createRabbit();
    

提交回复
热议问题