在不指定对象属性的情况下销毁对象 [英] Destructuring an object without specifying its properties

查看:81
本文介绍了在不指定对象属性的情况下销毁对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种优雅的解决方案,可以在不指定对象所有属性的情况下对对象进行销毁?

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.

推荐答案

这是with(){}构造所允许的:

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:

  • 您的代码很难阅读,因为无法区分1)来自外部作用域的变量2)局部变量3)来自对象的属性.

  • 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.

您的代码无法优化,因为JavaScript引擎无法告诉您变量的来源.

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

您的代码难以重构,因为如果您在obj中引入属性,则可能会掩盖一些现有的局部变量,例如:

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版本:您确实不希望这样做,这会使您的代码脆弱,难以阅读和重构.只需使用常规"解构语法挑选所需的片段即可.


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.

这篇关于在不指定对象属性的情况下销毁对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆