如果您没有针对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