How to write JavaScript with factory functions

前端 未结 6 1310
野趣味
野趣味 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:21

    I don't like these answers because they use the this keyword. You can avoid this altogether and still use a factory function like this:

    function createRabbit() {
        var speed = 3;
        return {
            getSpeed: function() {
                return speed;
            }
        }
    }
    
    var rabbit = createRabbit();
    console.log(rabbit.getSpeed());
    

    This guy has a good article about it: http://radar.oreilly.com/2014/03/javascript-without-the-this.html

提交回复
热议问题