4 ms·
Pointers on how to improve this (while maintaining your API) would be great :) var createOlympian = function() { return (function() { var attrs = []; //
by patrickdavey 10y ago
Pointers on how to improve this (while maintaining your API) would be great :)
var createOlympian = function() {
return (function() {
var attrs = []; // private variable for our olympian attributes
var olympian = {
name: function(name){
attrs['name'] = name;
return this;
},
sport: function(sport) {
attrs['sport'] = sport;
return this;
},
country: function(country) {
attrs['country'] = country;
return this;
},
log: function() {
console.log(attrs['name'] + ", " + attrs['sport'] + "; " + attrs['country']);
}
};
return olympian;
})();
};
- insin 10y agoBonus points for being meta? function createOlympian() { let props = ['name', 'sport', 'country'] let olympian = { log() { console.log(props.map(prop => this[prop]).join(', ')) } } props.forEach(prop => { olympian[prop] = function(value) { this[prop] = value return this } }) return olympian }
- tkxxx7 10y agoThis is neat, but those functions can only be used once.
- Spoom 10y agoThis would work, but attrs should really be an object (i.e. var attrs = {};), not an array, since you're storing string keys, and stylistically you can just use e.g. attrs.name instead of attrs['name'].