可能重复:
对象字面量声明中的自引用
在.js文件中,我有一个对象。我想在对象内部使用它的一些数据。类似于这样...?
obj = {
thing: 'thing',
things: this.thing + 's'
}
可能重复:
对象字面量声明中的自引用
在.js文件中,我有一个对象。我想在对象内部使用它的一些数据。类似于这样...?
obj = {
thing: 'thing',
things: this.thing + 's'
}
无法以这种方式创建对象,但有多种替代方案:
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;
}
};
function Thingy( thing ) {
this.thing = thing;
}
Thingy.prototype = {
getThings:function(){
return this.thing + 's';
}
}