JS分解为对象

时间:2018-06-21 10:12:44

标签: javascript node.js

我正在尝试在Node js v8中做到这一点

管理变量如下:

let management = {
    ip: '1.1.1.1',
    port: '443',
    username: 'admin',
    password: 'admin'   
}

constructor ({management,system,network,...other}) {

   this.management =  {
      ip ,
      port = 443,
      username = 'admin',
      password = 'admin',
    } = { ...management };
}

知道为什么收到消息

ip:ip,           ^

ReferenceError:未定义ip

评估应该不是从右到左,这样在尝试分配之前就破坏了管理? 您是否知道在没有更多代码的情况下如何以清晰的方式执行此操作的想法?

1 个答案:

答案 0 :(得分:0)

之所以会出现错误,是因为您将结构分解为从未在任何地方声明过的变量,并且在严格模式下会导致异常(而不是创建全局变量)。

顺便说一句,您不能destructure and construct an object literal at the same time。无论如何,您的代码只会将{ ...management }分配给this.management

您可能正在寻找

constructor ({management, system, network, ...other}) {
    const {ip, port = 443, username = 'admin', password = 'admin'} = management;
    this.management = {ip, port, username, password};
}

constructor ({management: {ip, port = 443, username = 'admin', password = 'admin'}, system, network, ...other}) {
    this.management = {ip, port, username, password};
}

constructor ({management, system, network, ...other}) {
    this.management = (({ip, port = 443, username = 'admin', password = 'admin'} => ({ip, port, username, password}))(management);
}