当前位置:Gxlcms > JavaScript > 消除JavaScript中的if

消除JavaScript中的if

时间:2021-07-01 10:21:17 帮助过:5人阅读

Email:longsu2010 at yeah dot net


我的脑海中总在浮现一个问题:“我能不能在写JavaScript的时候不出现if块?”

受Chris Owen对于SmallTalk的阐述启发我写出了类SmallTalk的无if实现。


Boolean.prototype.ifTrue = function (f) {
this && f();
return this;
};
Boolean.prototype.ifFalse = function (f) {
this || f();
return this;
};

// so you can write

(4 < 5).ifTrue(function () {
alert("It is true.");
}).ifFalse(function () {
alert("It isn’t true.");
});这个例子没有实际用途,但是在学习的角度来看是一个有趣的例子。

人气教程排行