Diasiare Diasiare - 4 months ago 23
Javascript Question

Destructuring assignment in function call while preserving the object

Is there a way to do something like the following?

f = (o:{a:x}) {
console.log(o);
console.log(x);
}
f({a:0});
//Should Print:
//{a:0}
//0


To get the same result as the this.

f = function(o) {
var {a:x} = o;
console.log(o);
console.log(x);
}
f({a:0});
//Prints
//{a:0}
//0


I would like to deconstruct the object inside the function parameters while also passing the object to the function so that the object can be modified.

Answer Source

No, it is not possible, consider:

var obj = {a:0}

function f (o: {a:x}) {} // not valid - unexpected token :
function f ({a}) {} // valid a === 0
function f ({a:x}) {} // valid x === 0, a is undefined - probably no use for this

The best you can do with the ES6 implementation is get access to nested props, not a reference to the object itself as well as nested props.

(would love to be proven wrong though, this is a feature I have looked for as well)