你能从自己的JSON对象中调用数据吗?

3

可能重复:
对象字面量声明中的自引用

在.js文件中,我有一个对象。我想在对象内部使用它的一些数据。类似于这样...?

obj = {
    thing: 'thing',
    things: this.thing + 's'
}

2
JSON和纯JavaScript字面量表示法都没有处理循环或相互依赖关系的内部/隐式方法。 - user166390
1个回答

6

无法以这种方式创建对象,但有多种替代方案:

var obj;
obj = {
  thing: 'thing'
};
obj.things = obj.thing + 's';

-or-

function Thingy(thing)
{
  this.thing = thing;
  this.things = thing + 's';
}
var obj;
obj = new Thingy('thing');

或者,如果您正在使用支持属性的浏览器:
function Thingy( thing )
{
  this.thing = thing;
}
Thingy.prototype = {
  get things() {
    return this.thing + 's';
  },
  set things(val) {
    //there are a few things horribly wrong with this statement,
    //it's just for an example, not useful for production code
    this.thing = val[val.length - 1] == 's' ? val.substr(0, val.length - 2) : val;
  }
};

如果您想了解更多相关信息,Jon Resig有一篇关于访问器和修改器(又称为getter和setter)的优秀文章
为了实现跨浏览器支持,请使用函数调用来获取复数形式并仅提供访问器。
function Thingy( thing ) {
  this.thing = thing;
}
Thingy.prototype = {
  getThings:function(){
    return this.thing + 's';
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接