我真的不明白你为什么要这样做,但这是可能的,尽管有一个讨厌的 hacky 解决方法。AFAIK,您实际上正在寻找的是一个神奇的属性(如someArray.length
属性)。
var foo = {val:'foo'};
foo.length = (function(that)
{
return function()
{
return that.val.length;
}
})(foo);
//at this point foo.length(); returns 3, but still requires parentheses
//so, build another closure, and assign a valueOf method to the lenth method:
foo.length.valueOf = (function(method)
{
return function()
{
return method();//call the length method
}
})(foo.length);
console.log(foo.length +1);//logs 4
foo.val += 'bar';
console.log(foo.length);//logs 6
//BUT:: be carefull!!
alert(foo.length);//coerces to string, we haven't redefined the toString method, so the function code will be alerted
alert(foo.length + '');//alerts 6
这只是为了向您展示,是的,理论上是可能的,但是请,请,不要使用这种过度污染的黑客......我还没有彻底测试过这个,但是 ATM,我已经注意到console.log(foo.length);
可以返回一个不同的值,不知道为什么,但是:
foo = {val:'foo'};
foo.length = (function(that){return function(){ return that.val.length;};})(foo);
foo.length.valueOf = (function(method){return function(){return method();};})(foo.length);
foo.length;//returns 3, great
foo.val += 'bar';
console.log(foo.length);//logged 3 at first, now it's back to logging 6!<-- don't trust this is the conclusion