0

Here's what I want to achieve:

var obj = {
  something: 1,
  someFunction: function () {
    return 'hello';
  }
};

wrap(obj).someFunction('hello'); // this should be different from obj.someFunction defined above
wrap(obj).something = 2; // this should still work

Basically, I want to 'wrap' an object and replace all the functions in it with something else.

Here's how I've defined the wrap function:

function hello (v) {
  return 'Hello ' + v;
}

function wrap (oldObj) {
  var newObj = {};

  for (var k in oldObj)
    Object.defineProperty(newObj, k, {
      get: function () {
        if (typeof oldObj[k] === 'function')
          return hello;
        return oldObj[k];
      },
      set: function (val) {
        oldObj[k] = val;
      }
    });

  return newObj;
}

(hello is just an example replacement function)

When I try to use this, everything in obj gets replaced with a function (i.e even obj.something, which was set to 1, is replaced with a function). I can't seem to find any issues with this code. I've tried debugging it and haven't found the issue yet.

What might be the issue? How else can I solve this problem?

Edit 1: I don't want to replace functions in the object itself, I want to create an entirely new object.

Ajay Tatachar
  • 383
  • 3
  • 16
  • the answer right there: "create an closure to maintain function name" – Karoly Horvath Oct 05 '14 at 13:57
  • I don't want to replace functions in the object that I'm wrapping, I want to create an entirely new object. – Ajay Tatachar Oct 05 '14 at 14:00
  • There's hardly a difference whether you create your setters on the original or a new object, what you were missing is the closure. – Bergi Oct 05 '14 at 14:06
  • the problem is by the time it got set, it is highly unlikely that your k iteration is the same as your property, extract the property creation to it's own methods, like eg: `function(source, target, property) { Object.defineProperty(target, property, { get: function() { return source[property]; }, set: function(val) { source[property] = val; } }); };` and use this one inside your iteration (call `funcProper(oldObj, newObj, k)`), this will make sure your property is correctly extracted – Icepickle Oct 05 '14 at 14:11
  • more info: http://jsfiddle.net/Icepickle/drfjhkkk/ – Icepickle Oct 05 '14 at 14:12

0 Answers0