Destructuring an object without specifying its properties

别来无恙 提交于 2019-12-12 13:42:59

问题


Is there an elegant solution to destructure an object without specifying all the object's properties?

I wondered if it was possible to use the spread operator but it seems like that's not possible because objects are not arrays!

I guess it may be considered a bad idea to blindly declare variables but I think this would be useful for very large objects.


回答1:


This is what the with(){} construction allowed:

var obj = {a: 1};
with (obj) {
  console.log(a);
}

This construct is however severely discouraged and basically deprecated (it throws an error in strict mode), because it has some major drawbacks:

  • Your code is hard to read, because it's impossible to tell apart 1) Variables from outer scopes 2) Local variables 3) Properties coming from the object.

  • Your code can't be optimized, because the JavaScript engine can't tell where your variables are coming from.

  • Your code is much harder to refactor, because if you introduce a property to your obj, it might shadow some existing local variable, exemple:


var obj = {};
var a = 1;
addSomeProperties(obj);
with (obj) {
  console.log(a); // the result here depends on whether or not "addSomeProperties" puts a property named "a" on "obj"
}

TL;DR version: you really don't want this, it makes your code brittle, hard to read&refactor. Just pick the pieces you want apart using the "normal" destructuring syntax.



来源:https://stackoverflow.com/questions/36797532/destructuring-an-object-without-specifying-its-properties

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