2011-08-31 72 views

回答

6

不能創建一個對象,方式,但是也有一些備選方案:

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

非常感謝! – fancy

相關問題