你能从中调用数据吗's自己的json对象

Can you call data from it's own json object?

本文关键字:自己的 对象 json 调用 数据      更新时间:2023-09-26

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

在一个.js文件中,我有一个对象。我想使用它本身的一些数据。像。。。?

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

您不能以这种方式创建对象,但是有许多替代方案:

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

-或-

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';
  }
}