Chapter 1: Types
Bah! We’re going to use this rough definition (the same one that seems to drive the wording of the spec): a type is an intrinsic, built-in set of characteristics that uniquely identifies the behavior of a particular value and distinguishes it from other values, both to the engine and to the developer.
Armed with a full understanding of JavaScript types, we’re aiming to illustrate why coercion’s bad reputation is largely overhyped and somewhat undeserved – to flip your perspective, to seeing coercion’s power and usefulness.
We’ll see.
If you want to test for a null
value using its type, you need a compound condition:
var a = null;
(!a && typeof a === "object"); // true
null
is the only primitive value that is “falsy” but that also returns "object"
from the typeof
check.
It’s tempting for most developers to think of the word “undefined” and think of it as a synonym for “undeclared.” However, in JS, these two concepts are quite different.
An “undefined” variable is one that has been declared in the accessible scope, but at the moment has no other value in it. By contrast, an “undeclared” variable is one that has not been formally declared in the accessible scope.
Consider:
var a;
a; // undefined
b; // ReferenceError: b is not defined
Error message返回”b is not declared”更准确。
There’s also a special behavior associated with typeof
as it relates to undeclared variables that even further reinforces the confusion. Consider:
var a;
typeof a; // "undefined"
typeof b; // "undefined"
The typeof
operator returns "undefined"
even for “undeclared” (or “not defined”) variables.
可以用typeof
来检查一个变量是否被声明了(难道没有try..catch
么)。
Another way of doing these checks against global variables but without the safety guard feature of typeof
is to observe that all global variables are also properties of the global object, which in the browser is basically the window
object. So, the above checks could have been done (quite safely) as:
if (window.DEBUG) {
// ..
}
if (!window.atob) {
// ..
}
Unlike referencing undeclared variables, there is no ReferenceError
thrown if you try to access an object property (even on the global window
object) that doesn’t exist.
检查是否被声明的另一个思路,但只能对全局变量有用。