在JavaScript中,有没有一种方法可以使用未初始化的实例变量来创建对象文字?

目的是为了使用通用代码,允许使用for-in循环迭代成员以与其他类似对象并行地初始化它们。目前,我只需要为成员保留临时的伪值(包括“ undefined”),因此我想知道是否有一种方法可以避免这种情况。

最佳答案

这很漂亮。取决于Object.definedProperty

让我们创建一个对象

var obj = Object.create({});


定义一些enumerable属性。当我们遍历对象时,这些将出现

Object.defineProperty(obj, 'hardwork', {
  configurable: true,
  enumerable:   true,
  get: function() {
    // caution: hard work below!
    console.log("hard work began");
    return Math.random();
  }
});

Object.defineProperty(obj, 'reallyhardwork', {
  configurable: true,
  enumerable:   true,
  get: function() {
    // caution: really hard work below!
    console.log("really hard work began");
    return [Math.random(), Math.random(), Math.random()];
  }
});


这是不可枚举的财产;它不会包含在for..in循环中

Object.defineProperty(obj, 'hidden', {
  configurable: true,
  enumerable:   false,
  get: function() {
    console.log("hidden work happening now!");
    return "you should not see this";
  }
});


最后,让我们实际做一些工作

console.log("begin working");
for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(obj[prop]);
  }
}
console.log("work ended");


输出量

"begin working"
"hard work began"
0.038129367399960756
"really hard work began"
[ 0.9397948638070375, 0.6731829405762255, 0.2854277777951211 ]
"work ended"


注意:hidden属性未显示在输出中,但是如果需要它仍然可用。

obj.hidden
// => hidden work happening now!
// => you should not see this




将此与以下内容进行比较

var obj = {
  hardwork: Math.random(),
  reallyhardwork: [Math.random(), Math.random(), Math.random()],
  hidden: "you should not see this"
};


这些Math.random()调用在定义对象时运行,这意味着所有艰苦的工作都已经预先完成。不会像上面的示例那样在迭代过程中延迟加载。另请注意,如果您希望不将任何属性包含在循环中,则这种方法将行不通。您将在下面看到显示了hidden属性。

// no work is done except for iterating through values that have already been defined
for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(obj[prop]);
  }
}


输出量

0.7174121951684356
[ 0.7939756268169731, 0.4218691026326269, 0.8476794681046158 ]
"you should not see this"

关于javascript - 使用未初始化的成员创建JS对象文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17711527/

10-14 17:11
查看更多