lundi 18 janvier 2016

Looking for a better way to attach reflection methods with objects in Javascript

I'm looking for a fast and clean way to attach a couple of reflection methods on objects located inside an array, but I don't want to monkey-patch the objects. The objects themselves may be of varying sizes as they're returned from a dynamic JSON endpoint, thus not going down the route of ObjWrapper(obj) { this.foo = obj.foo; }.

I've come up with the following code, but I do feel there would be a more elegant way to achieve the same result. I would be happy to explore the use of Lodash's functions:

var objs = [{foo:'bar'}, {foo:'baz'}];

function ObjWrapper(obj){
  var self = this;
  // Inherit all the shallow object properties
  Object.keys(obj).forEach(function(key){
    self[key] = obj[key];
  });
}

ObjWrapper.prototype.isBar = function() {
  return this.foo === 'bar';
}

ObjWrapper.prototype.isBaz = function() {
  return this.foo === 'baz';
}

objsWrapped = objs.map(function(obj){
  return new ObjWrapper(obj);
});

objsWrapped.forEach(function(objWrapped){
  console.log(objWrapped.isBar());
  console.log(objWrapped.isBaz()); 
});

I'm not seeing a performance difference in this approach over using a static function to evaluate the object logic: http://ift.tt/1P1uVX9

For clarity, the question is; can this be written better?





Aucun commentaire:

Enregistrer un commentaire