Created
          September 14, 2011 00:46 
        
      - 
      
 - 
        
Save vstarck/1215584 to your computer and use it in GitHub Desktop.  
    Inyección de getters/setters en objetos
  
        
  
    
      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
    
  
  
    
  | /** | |
| * 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