0

See the following example:

var foo = { bar : 0 };

function modify(obj)
{
    obj = {};
}

modify(foo);

console.log(foo);

My first object in the global scope remains unchanged. Because the function did not replace the object but a copy of the reference.

So my question is simple. Does anyone know of a work-around way, or are there ECMAScript features in currently development or have there been attempts to make this possible at all?

Thanks.

Mister Happy
  • 124
  • 7

1 Answers1

1

You can't change the binding of the variable that you were called with. But since you receive a reference to the same object, you can modify the object itself. So you can remove all the properties:

function modify(obj) {
  Object.keys(obj).forEach(function(k) {
    delete obj[k];
  });
}

var foo = { a: 3 };
console.log(foo);
modify(foo);
console.log(foo);
Barmar
  • 741,623
  • 53
  • 500
  • 612