初始化JavaScript对象及其属性的好方法?

Cod*_*ike 17 javascript

我知道我可以像这样初始化一个JS对象数组:

var things = [
  {
    prop1: 'foo',
    prop2: 'bar'
  },
  {
    prop1: 'foo',
    prop2: 'bar'
  }
];
Run Code Online (Sandbox Code Playgroud)

我想我会称这些'匿名'类型(抱歉,我使用的是C#/.NET语言).

如果我希望这些原型相同怎么办?所以我定义了一个构造函数:

var Thing = function Thing() {
};

Thing.prototype.prop1 = 'default value';
Thing.prototype.prop2 = 'default value';
Run Code Online (Sandbox Code Playgroud)

现在我想要上面原始代码中的两个项目都是Things.有没有办法做到这一点?

如果我猜,我会说可能是这样的:

var things = [
  new Thing() {
    prop1: 'foo',
    prop2: 'bar'
  },
  new Thing() {
    prop1: 'foo',
    prop2: 'bar'
  }
];
Run Code Online (Sandbox Code Playgroud)

这基本上是C#对象的初始化语法.我想避免的是:

var thing1 = new Thing();
thing1.prop1 = 'foo';
thing1.prop2 = 'bar';
var thing2 = new Thing();
thing2.prop1 = 'foo';
thing2.prop2 = 'bar';
var things = [thing1, thing2];
Run Code Online (Sandbox Code Playgroud)

编辑:

我还应该注意,我的原型还包含一些共享的函数.实际上我有数组嵌套3深,所以它更像是:

{
   [
    { 
      [
        {},
        {}
      ]
    },
    {
      [
        {},
        {}
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么我希望像这样初始化所有内联而不是逐行设置每个属性.

Alc*_*iar 13

var Thing = function(params) {
  this.prop1 = params.prop1;
  this.prop2 = params.prop2;
};

var things = [
  new Thing({
    prop1: 'foo',
    prop2: 'bar'
  }),
  new Thing({
    prop1: 'foo',
    prop2: 'bar'
  }),
];
Run Code Online (Sandbox Code Playgroud)

  • 将此标记为答案,因为它在我的情况下效果最佳.它还允许我做可选属性,例如:`function Thing(params){this.name = params.hasOwnProperty("name")?params.name:"默认"; }` (2认同)

Sid*_*gal 11

你没有使用你的'构造函数'.它首选初始化你的构造函数中的值:

var Thing = function Thing(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
};
Run Code Online (Sandbox Code Playgroud)

然后做:

var thing1 = new Thing("foo", "bar");
var thing2 = new Thing("foo", "bar");
Run Code Online (Sandbox Code Playgroud)