3
可能重複:
Self-references in object literal declarations你可以從它自己的json對象調用數據嗎?
在.js文件中我有一個對象。我想在其內部使用它的一些數據。就像是...?
obj = {
thing: 'thing',
things: this.thing + 's'
}
可能重複:
Self-references in object literal declarations你可以從它自己的json對象調用數據嗎?
在.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有一個great post about accessors and mutators,AKA獲得者和二傳手。
對於跨瀏覽器支持,堅持使用一個函數調用的複數形式,並且只提供一個存取:
function Thingy(thing) {
this.thing = thing;
}
Thingy.prototype = {
getThings:function(){
return this.thing + 's';
}
}
非常感謝! – fancy
既不JSON也不平原* JavaScript的文字符號*具有用於處理週期內/隱式方法或相互依存關係。 – 2011-08-31 23:09:11