在javascript中向const分配值

时间:2018-11-06 05:16:34

标签: javascript ecmascript-6 const variable-assignment destructuring

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

1

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

      return(someOtherComponent);
    }

不同吗?

2

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

      return(someOtherComponent);
    }

3

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

      return(someOtherComponent);
    }

我相信 3 片段为函数中的自变量赋值,而 2 3 可能相同,这是正确的理解吗?

如果不是,那么有人可以向我解释这种赋值的相关逻辑,并为这些将值赋给常量的方法正确地用专业术语吗?

1 个答案:

答案 0 :(得分:4)

首先解决所有疑问:赋值总是从右到左完成,就像“普通JS”和大多数编程语言一样。

但是在ES6中,您有很多新语法可以简化分配。

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

当变量名称与属性名称相同时,会混合使用所谓的 destructuring 和一些语法糖,它将变量“从”移出,从而有助于同时分配多个变量。一个对象(或数组!),

这不适用于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)

// 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)

// 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)

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*/
  };

以上是通过保持相同名称来从现有变量重新分配新对象的快捷方式语法。

相关问题