在Javascript中声明空对象属性的简写,有没有?

时间:2011-05-19 10:28:51

标签: javascript object properties

我需要在脚本中声明很多对象属性,我想知道是否有任何方法可以缩短它:

Core.registry.taskItemSelected;
Core.registry.taskItemSelected.id;
Core.registry.taskItemSelected.name;
Core.registry.taskItemSelected.parent;
Core.registry.taskItemSelected.summary;
Core.registry.taskItemSelected.description;

2 个答案:

答案 0 :(得分:12)

那不行吗?

Core.registry.taskItemSelected = {
  id: null,
  name: null,
  parent: null,
  ...
};

答案 1 :(得分:1)

这样的事情应该有效:

var props = ["id", "name", "parent", ...];
Core.registry.taskItemSelected = {};
for (var i = 0; i < props.length; i++)
   Core.registry.taskItemSelected[props[i]] = "";

编辑:在OP评论之后,这里是更好的版本,具有相同的最终结果:

Object.prototype.declare = function (varArray) {
    for (var i = 0; i < varArray.length; i++) {
        this[varArray[i]] = {};
    }
};

//usage:
var props = ["id", "name", "parent"];
Core = {};
Core.declare(props);

现场测试用例:http://jsfiddle.net/5fRDc/