Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created August 8, 2012 06:27
Show Gist options
  • Select an option

  • Save wilmoore/3292822 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/3292822 to your computer and use it in GitHub Desktop.
Experiment: Which API is more intention revealing?
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
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
@wilmoore
Copy link
Author

wilmoore commented Aug 8, 2012

The example sucks, I know :)

@wilmoore
Copy link
Author

wilmoore commented Aug 8, 2012

This gets really useful once Proxies are supported.

@wilmoore
Copy link
Author

wilmoore commented Aug 8, 2012

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?

@wilmoore
Copy link
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