Object oriented javascript with prototypes vs closures

前端 未结 5 1238
醉酒成梦
醉酒成梦 2020-11-28 19:29

I\'m curious what the difference is between the following OOP javascript techniques. They seem to end up doing the same thing but is one considered better than the other?

5条回答
  •  孤街浪徒
    2020-11-28 20:11

    The former method is how JavaScript was intended to be used. The latter is the more modern technique, popularised in part by Douglas Crockford. This technique is much more flexible.

    You could also do:

    function Book(title) {
        return {
            getTitle: function () {
                return title;
            }
        }
    }
    

    The returned object would just have an accessor called getTitle, which would return the argument, held in closure.

    Crockford has a good page on Private Members in JavaScript - definitely worth a read to see the different options.

提交回复
热议问题