Skip to content

Instantly share code, notes, and snippets.

@vstarck
Created September 14, 2011 00:46
Show Gist options
  • Save vstarck/1215584 to your computer and use it in GitHub Desktop.
Save vstarck/1215584 to your computer and use it in GitHub Desktop.
Inyección de getters/setters en objetos
/**
* Xetteriza el objeto
*
* @param {Object} obj
* @param {Array} props
* @return {Object}
*/
var xetterize = (function() {
/**
* Formatea el string para que sea
* apto como nombre de metodo
*
* @private
* @param {String} str
* @return {String}
*/
function format(str) {
return str.replace(/[-_\s]+(.)/g, function(match, char) {
return char.toUpperCase();
}).replace(/^([a-z])/, function(match, char) {
return char.toUpperCase();
});
}
return function(obj, props) {
for(var i = 0, l = props.length; i < l; i++) {
(function(prop, formatted) {
obj['get' + formatted] = function() {
return prop;
};
obj['set' + formatted] = function(value) {
this[prop] = value;
return this;
};
})(props[i], format(props[i]));
}
return obj;
}
})();
var person = {};
xetterize(person, ['name', 'age', 'lastname', 'job']);
console.dir(person);
/*
getAge
function()
getJob
function()
getLastname
function()
getName
function()
setAge
function()
setJob
function()
setLastname
function()
setName
function()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment