Created
August 8, 2012 06:27
-
-
Save wilmoore/3292822 to your computer and use it in GitHub Desktop.
Experiment: Which API is more intention revealing?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Game(){ | |
| var total_score = 0; | |
| var scoring_map = {ghost: 10, pellet: 1, fruit: 5}; | |
| Object.defineProperties(this, { | |
| score: { get: function(){ return total_score; } } | |
| }); | |
| this.eat = function (edible){ | |
| total_score += scoring_map[edible] ? scoring_map[edible] : 0; | |
| } | |
| } | |
| var pacman = new Game(); | |
| pacman.eat('ghost'); | |
| pacman.eat('fruit'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('not-in-scoring-map'); | |
| console.log('Score:', pacman.score); // 19 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Game(){ | |
| // property + public accessor for (total score) | |
| var total_score = 0; | |
| this.score = function (){ return total_score; }; | |
| // other properties | |
| var scoring_map = {ghost: 10, fruit: 5, pellet: 1}; | |
| // public eat function (method) | |
| this.eat = function eat(edible){ | |
| total_score += scoring_map[edible] ? scoring_map[edible] : 0; | |
| }; | |
| } | |
| var pacman = new Game(); | |
| pacman.eat('ghost'); | |
| pacman.eat('fruit'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('pellet'); | |
| pacman.eat('not-in-scoring-map'); | |
| // This only works because the called function is a closure; so yes, the function totalScore() must be "applied" in order to retrieve the property value. | |
| console.log('Score:', pacman.score()); // 19 |
Author
Author
Huh....funny to come back to this much later. I no longer feel the ES5 method is better. It's way more verbose for little/no value. Calling a function to get/set is actually fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, the non-es5 version has the benefit of not needed to use the new syntax; however, to me, it seems less intention revealing (though JavaScript veterans may be used to this nomenclature).
The es5 version seems to be obvious in intent. I also prefer "pacman.score" vs. "pacman.score()". I also dig the fact that I have control over which properties are enumerable (think: hasOwnProperty) vs. having to hack that in or play around with what goes on the "prototype" and what doesn't.
That being said...what say you?