Destructure object parameter, but also have reference to the parameter as an object? [duplicate]

送分小仙女□ 提交于 2019-12-01 02:22:09

问题


With ES6 you can destructure objects in function arguments:

({name, value}) => { console.log(name, value) }

The equivalent ES5 would be:

function(params) { console.log(params.name, params.value) }

But what if I would like a reference both to the params object and the nested properties value and name? This is the closest I got, but the drawback is that it won't work with arrow functions because they do not have access to the arguments object:

function({name, value}) {
  const params = arguments[0]
  console.log(params, name, value)
}

回答1:


arguments isn't available in arrow functions, and this affects how function parameters should be consistently treated in ES6.

If original parameter is used, it should be destructured inside function:

(param) => {
  const {name, value} = param;
  // ...
}

If several arguments are expected and some argument negotiation takes place (for example, similarly to arguments.length), rest parameter should be used:

(...args) => {
  const [param] = args;
  // ...
}

Boilerplate variable destructuring has its benefits; it's easier this way to debug param or args at breakpoint even if they aren't currently in use.




回答2:


What about next:

function({name, value}, params=arguments[0]) {
    console.log(params, name, value)
}

Or:

function(params, {name, value} = params) {
    console.log(params, name, value)
}


来源:https://stackoverflow.com/questions/49075043/destructure-object-parameter-but-also-have-reference-to-the-parameter-as-an-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!