在 javascript right-left 和 left-right 中为 const 赋值

TGW*_*TGW 1 javascript constants destructuring variable-assignment ecmascript-6

我正在查看一个反应代码库,在那里我看到了这种类型的代码片段

1

const SomeComponent= function(props) {
      const{
        child,
        style,
        disable,
        ...otherParam
      } = props;

      return(someOtherComponent);
    }
Run Code Online (Sandbox Code Playgroud)

是不是不同于

2

const SomeComponent= function(props) {
      const props = {
        child,
        style,
        disable,
        ...otherParam
      };

      return(someOtherComponent);
    }
Run Code Online (Sandbox Code Playgroud)

或者

3

const SomeComponent= function(props) {
      props = {
        child,
        style,
        disable,
        ...otherParam
      };

      return(someOtherComponent);
    }
Run Code Online (Sandbox Code Playgroud)

我相信3次片断受让人价值已有param来作为函数的参数,而23可能是一样的,这是正确的认识?

如果不是,那么有人可以向我解释这种分配的相关逻辑和正确的技术术语到这些将值分配给常量的方法吗?

Pac*_*ac0 5

首先解决任何疑问:赋值总是从右到左完成,就像在“plain olde JS”和大多数编程语言中一样。

然而在 ES6 中,你有很多新的语法来简化赋值。

也许您会感到惊讶的是,当某些“对象结构”位于左侧时。

当变量的名称与属性名称相同时,混合了所谓的解构和一些语法糖,它有助于同时分配许多变量,通过将它们从对象(或数组!)中“取出”,

这不是特定于const,它对任何赋值都有效,并且此语法也可用于函数参数。


1:解构

(从右侧的一个对象或一个数组一次分配左侧的多个值)

例子 :

// here a and b take the value from the source.a and source.b, respectively

const source = { a: 1, b: 2, c: 3}
const {a, b} = source
console.log(a,b)
Run Code Online (Sandbox Code Playgroud)
// same for arrays
// here a and b have taken the first and the second value of the source array, repectively.

const source = [1, 2, 3]
const [a, b] = source
console.log(a,b)
Run Code Online (Sandbox Code Playgroud)
// and you can use `...` to get *all the other values*
// here a will take the first value, and b will get all the other values, which is `[2, 3]`

const source = [1, 2, 3]
const [a, ...b] = source
console.log(a,b)
Run Code Online (Sandbox Code Playgroud)

2 和 3:分配的对象字面量

它们几乎是普通的 ES5 JavaScript 对象分配,带有少量语法糖以避免重复name: name.

props 左侧分配了一个新对象,其中包含在右侧创建的对象文字。


2 和 3 之间的唯一区别是,在示例 2 中,const props在函数作用域中创建了一个新绑定,它实际上对参数隐藏了props

在实施例3,现有的props作为参数被突变将被分配一个新的值。

老实说,我认为示例 2 是一个编程错误

无论如何,2 和 3 都与这个“伪 javascript”相同:

// here we susppose that there are some exiting `child` `style` `disable` variable, and an array `otherParam`
props = {
    child: child,
    style: style,
    disable: disable,
    otherParam: /* an array which is a copy of an existing "otherParam" array , with spread operator*/
  };
Run Code Online (Sandbox Code Playgroud)

以上是通过保持相同名称从现有变量中读取新对象的快捷语法。