What are patterns you could use with prototype inheritance that you cannot with class?

后端 未结 4 1471
长发绾君心
长发绾君心 2021-02-05 12:37

Everyone seems to generally agree that prototype inheritance is simpler and more flexible than class inheritance. What I have not seen in the literature that I\'ve read is very

4条回答
  •  野性不改
    2021-02-05 12:57

    Ok, I'll add one, use the fact that prototype links are live to monkey-patch methods for a whole class of objects:

    var Cat = function(catName) {
        this.catName = catName;
    };
    Cat.prototype.meow = function() {
        console.log(this.catName+" says meow");
    }
    var mittens = new Cat("Mittens");
    var whiskers = new Cat("Whiskers");
    mittens.meow(); // "Mittens says meow"
    whiskers.meow(); // "Whiskers says meow"
    
    // All cats are now angry
    Cat.prototype.meow = function() {
        console.log(this.catName+" says hissssss");
    }
    mittens.meow(); // "Mittens says hissssss"
    whiskers.meow(); // "Whiskers says hissssss"
    

    This would be useful if you have objects that suddenly need to start acting in a completely different yet consistent manner in response to some sort of global event. Maybe for something like:

    • Themes and skinning
    • Whether a page is functioning in "online mode" or "offline mode" (while online all queries are stored/retrieved via ajax, while offline queries redirect to browser storage)

提交回复
热议问题