Читать книгу Reliable JavaScript - Lawrence Spencer - Страница 10
INTRODUCTION
THE EASE OF WRITING TRULY DISASTROUS CODE IN JAVASCRIPT
ОглавлениеPart of the problem, which she has only recently begun to outgrow, was her years spent as a page-scripting language. In that limited sphere, there was no harm in making a variable or function global. If a variable was misspelled, the effects were limited and easy to track down. (By the way, the effect would likely be to create yet another global.) If the architecture was sloppy.. well, how much architecture can there even be on just one web page?
Compounding the potential for error was the lack of a compiler. Server-side programs in C# or Java are guaranteed to be at least syntactically correct before they are run. JavaScript must start and hope for the best. A misspelled variable, or a call to a non-existent function, can lurk in the code for months until a particular execution path is followed.
And then there are the quirks. Ah, those endearing, maddening quirks.
At the top of the list must be the distinction between ==
(equality with type coercion) and ===
(without). A great idea, but so hard for programmers primarily trained in other languages to get used to!
Never is JavaScript more coquettish than when it comes to truth and falsehood. She has a notion of “truthy” and “falsy” that confuses all but the most determined suitors. Zero is a falsy value so, thanks to type coercion, the expression
is true
. But not for the reason you think. The value false
is coerced to a number, which is 0
(true
would convert to 1
). Next, the string '0'
is also coerced to a number. That is also 0
, so the result is true
.
However,
evaluates to false
because the left-hand false
, again coerced to the number 0
, is compared to the string 'false'
, also coerced to a number. Except 'false'
is not a number at all so the second conversion yields NaN
(Not a Number) and the equality fails. Ah, JavaScript.
She is always up for a little fun. If you declare the function
and call it thus:
JavaScript will let the call proceed with the variable you
undefined, just for the fun of watching you try to play with someone who isn't there.
We could go on and on. There are surprising scoping rules, a unique “prototypal” inheritance mechanism, automatic and sometimes incorrect semicolon insertion, the ability of one object to borrow a function from a totally unrelated object, et cetera, et cetera.
With globals popping into existence unbidden, an almost total lack of architectural tradition, a questionable relationship to the truth, and more quirkiness than you'd find at a cosplay convention, it's a wonder that JavaScript has done as well as she has in the world.
Believe it or not, it gets worse before it gets better. Even if you get it right, it can go wrong oh so easily.