如何动态声明对象的属性

时间:2018-03-21 09:41:35

标签: javascript constructor

我想创建一个新的构造函数实例,它有一个包含对象数组的对象,并且在其中一个对象中,我想映射传递的参数。我收到这样的错误:

Uncaught SyntaxError: Unexpected token .

我的代码:



function Constructor (arg1, arg2, arg3, arg4) {
  this.arg1 = arg1;
  this.arg2 = arg2;
  this.arg3 = arg3;
  this.arg4 = arg4;

  this.storage = {
    arg1: {
      open: arg2, 
      dataset: [{
        drink: arg3.map(drink => ({
          drink,
        food: arg4
        }))
      }]
    }
}};


var diner = new Constructor ('restaurant', 'daily', ['wine', 'beer', 'vodka'], 'bread');

console.log(diner.storage);




Codepen: https://codepen.io/anon/pen/pLeOLp?editors=1111

我纠正了错别字。

我怎样才能通过' restaurant'进入' arg1'在this.storage = { arg1: { ...

之内

1 个答案:

答案 0 :(得分:0)

  

如何将'restaurant'传递给this.storage中的'arg1'= {arg1:{...

我只能假设你想这样做:

function Constructor (arg1, arg2, arg3, arg4) {
  this.arg1 = arg1;
  this.arg2 = arg2;
  this.arg3 = arg3;
  this.arg4 = arg4;

  this.storage = {
    [arg1]: {
      open: arg2, 
      dataset: [{
        drink: arg3.map(drink => ({
          drink,
        food: arg4
        }))
      }]
    }
}};


var diner = new Constructor ('restaurant', 'daily', ['wine', 'beer', 'vodka'], 'bread');

console.log(diner.storage);

这会在storage restaurant上为您提供属性