無意中看到一篇老外寫的討論javascript中undefined和null的文章,俺也學人家翻譯一回。發現這英文不用也是要生鏽的。
英文原文:http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html
JavaScript undefined vs. null
I was reading a modern, popular book on JavaScript last night and was disappointed by the handling of null. The author started out doing a lot of checking like:
昨天晚上,我在閱讀一本javascript的暢銷書,書中對null的處理讓我失望。作者起初做了很多這樣的檢查:
if (foo == null) { alert('foo is not set.'); }
Then told the reader that they could just remove the == null because javascript knows you mean "== null"
然後告訴讀者,可以移除“== null”,因為javascript知道你這樣寫表示"== null"。
What?! This isn't why you don't check for equality with null. It's because foo == null doesn't even remotely do what most people think it does in this context.
說啥呢。這並不是你不檢查等於null的原因。因為foo == null 甚至沒有間接的做,在這個上下文中很多人以為它會做的(檢查null)。
It's a commonly held belief that uninitialized properties in JavaScript are set to null as default values. People believe this mostly for 2 reasons: 1) foo == null returns true if foo is undefined and 2) authors don't teach JavaScript properly.
通常認為,在javascript中,未初始化的屬性,預設被設定成null。這基於兩個原因:1)如果foo是undefined,foo == null 返回true。2)作者沒有正確的講授javascript。
A property, when it has no definition, is undefined. Put that way, it's pretty obvious.
一個屬性在未定義時,是undefiend。這種情況是很顯然的。
null is an object. It's type is null. undefined is not an object, it's type is undefined. That part is less obvious.
null是一個object,它的類型是null。(註:這裡可能是筆誤。null的類型是object。) undefined不是一個object,它的類型是undefined。這部分不太明顯。
The real trouble is that == does type coercion. === checks for both type and value and is the most intuitive form of equality in JavaScript, in my opinion.
真正的問題在於==做了類型轉換。=== 同時檢查類型和值,我認為這是javascript中表示相等的最直觀的形式。
I fired up a Jash console to hopefully clear things up for you.
我啟動Jash控制台,希望能為你們整理一下。
>> window.hello
null
>> window.hello.something
window.hello has no properties
>> window.hello == null
true
>> window.hello === null
false
>> window.hello === undefined
true
>> if (window.hello) { alert('truthy'); } else { alert('falsy'); } // will print falsy.
null
>> window.hello == undefined
true
>> null == undefined
true // there's the rub, sir.
>> null
null
>> undefined
null
>> typeof null
object
>> typeof undefined
undefined
So people write
if (foo == null) {
foo = "Joe";
}
When what they really mean is
if (!foo) {
foo = "Joe";
}
If you find yourself with a lot of null checks in your JavaScript, set aside some time and watch Douglas Crockford's "The JavaScript Programming Language" talk on Yahoo Video. It's part 1 of a 3-part series of excellent and enlightening talks.
如果你發現在你的javascript代碼中有很多的null檢查,抽點時間看看Yahoo Video上Douglas Crockford的《JavaScript程式設計語言》的演講。它是一系列頗具啟發性的優秀演講中的第一部分。