Object oriented javascript with prototypes vs closures

前端 未结 5 1228
醉酒成梦
醉酒成梦 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:03

    It's also a little bit about re-usability under the hood. In the first example with the Function.prototype property usage all the instances of the Book function-object will share the same copy of the getTitle method. While the second snippet will make the Book function execution create and keep in the heap 'bookshelf' different copies of the local closurable book object.

    function Book(title) {
        var book = {
            title: title
        };
        book.getTitle = function () {
            return this.title += '#';
        };
        return book;
    }
    
    var myBook = Book('War and Peace');
    var myAnotherBook = Book('Anna Karenina');
    alert(myBook.getTitle()); // War and Peace#
    alert(myBook.getTitle()); // War and Peace##
    alert(myAnotherBook.getTitle()); // Anna Karenina#
    alert(myBook.getTitle());// War and Peace###
    

    The prototype members exist in the only copy for all the new instances of the object on the other hand. So this is one more subtle difference between them that is not very obvious from the first sigh due to the closure trick.

提交回复
热议问题