Home >Web Front-end >JS Tutorial >Eliminate if in JavaScript

Eliminate if in JavaScript

高洛峰
高洛峰Original
2016-11-28 11:28:471428browse

Email:longsu2010 at yeah dot net


A question always pops up in my mind: "Can I write JavaScript without if blocks?"

Inspired by Chris Owen's explanation of SmallTalk, I wrote An if-less implementation of class SmallTalk.


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.");
});This example has no practical use, but it is an interesting example from a learning perspective.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn