2015年9月17日星期四

[笔记] Speaking JavaScript Chapter 9 Operators

1. Equality Operators


Equality is not customizable. Operators can't be overloaded in JavaScript, and you can't customize how equality works. There are some operations where you often need to influence comparison-for example, Array.prototype.sort(). That method optionally accepts a callback that perform all comparisons between elements.

Pitfall: NaN !== NaN

Normal(Lenient) Equality (==, !=)

The following comparison ensures that x is neither undefined nor null:

if (x != null) ...


Use case: working with numbers in strings

if (x == 123) ...

The preceding checks whether x is either 123 or '123'. It is better to be explicit:

if (Number(x) === 123) ...


Use case: comparing wrapper instances with primitives

> 'abc' == new String('abc')
true

> new String('abc') == new String('abc')
false

Lenient equality does not work between wrapped primitives.

2. The Plus Operator


You evaluate an addition:

value1 + value2
by taking the following steps:
(1) Ensure that both operands are primitives. Objects obj are converted to primitives
via the internal operation ToPrimitive(obj) (refer to “Algorithm: ToPrimitive()—
Converting a Value to a Primitive” on page 79), which calls obj.valueOf() and,
possibly, obj.toString() to do so. For dates, obj.toString() is called first.
(2) If either operand is a string, then convert both to strings and return the concatenation
of the results.
(3) Otherwise, convert both operands to numbers and return the sum of the results.


3. Special Operators


What is void for?
(1) void 0 as a synonym for undefined
(2) Discarding the result of an expression
If you want to open a new window without changing the currently displayed content, you can do the following:
javascript:void window.open("http://example.com/")


Pitfall: typeof null
Unfortunately, typeof null is 'object'. The following function checks whether value is an object:
function isObject(value) {
return (value !== null
&& (typeof value === 'object'
|| typeof value === 'function'));
}

没有评论:

发表评论