是否有可能实现这种(确切的)语法
我的回答是:没有。
我尝试了以下方法来解决这个谜题,它似乎不起作用。
然而,我认为这是要走的路。
免责声明:这只是一些解谜,而不是真实世界的代码。
var Queue = function () {};
Queue.prototype.sizeValue = 2;
Queue.prototype.size = function ()
{
return this.sizeValue;
};
Queue.prototype.pop = function ()
{
// EDIT: yes, it's not popping anything.
// it just reduces size to make toString()
// and valueOf() return nulls.
this.sizeValue -= 1;
};
Queue.prototype.valueOf = function ()
{
if (this.size() > 0) {
return this.sizeValue;
}
return null;
};
Queue.prototype.toString = function ()
{
if (this.size() > 0) {
return "Queue["+this.sizeValue+"]";
}
return null;
};
var test = new Queue();
while (test) {
test.pop();
if (test.size() < -1) {
// just to get you out of the loop while testing
alert("failed");
break;
}
}
alert("out:"+test);
在 toString() 和 valueOf() 中放置警报,以查看它们不会被条件触发while (test) {}
。