如果您沒有針對Internet Explorer用戶,請嘗試使用getter和setter方法。
var x = 5;
function myObj()
{
this.master = 17;
this.getSlave1 = function() {return this.master + x;},
this.getSlave2 = function() {return (this.master/2.2) + 1;},
this.getSlave3 = function() {return Math.floor(this.getSlave2());}
}
myObj.prototype = {
get slave1() {
return this.getSlave1();
},
get slave2() {
return this.getSlave2();
},
get slave3() {
return this.getSlave3();
}
};
在行動:
window.onload = function()
{
o = new myObj();
document.write("Master: "+o.master+"</br>");
document.write("Slave 1: "+o.slave1+"</br>");
document.write("Slave 2: "+o.slave2+"</br>");
document.write("Slave 3: "+o.slave3+"</br></br>");
o.master = 42;
document.write("Master: "+o.master+"</br>");
document.write("Slave 1: "+o.slave1+"</br>");
document.write("Slave 2: "+o.slave2+"</br>");
document.write("Slave 3: "+o.slave3+"</br>");
}
產生輸出:
Master: 17
Slave 1: 22
Slave 2: 8.727272727272727
Slave 3: 8
Master: 42
Slave 1: 47
Slave 2: 20.09090909090909
Slave 3: 20
此代碼將從不在Internet Explorer中,過去,現在或將來的任何版本工作。但是,它的從屬值仍然可以使用getSlaveX()
函數訪問。
如果你打算採取這種方法,我寧願將主屬性作爲私有成員,所以不能直接設置,導致從屬屬性錯誤。你必須用構造函數替換文字對象符號。 – lincolnk 2010-09-19 01:05:21