开发者

Why does "Javascript the Good Parts" claim that "A property value can be any Javascript value except for undefined"?

As mentioned in the topic JS the Good Parts seems to claim that a property value can't be undefined. However if you do the following in Chrome's console for example:

var foo = {}
foo.bar = undefined
foo

Then click to expand the foo object you can 开发者_如何转开发still see that foo contains a property called bar with the value undefined. Of course from the Javascript side you can't tell the difference between foo.bar returning undefined and foo.unexistingproperty returning undefined. But what is the point of the console still clinging to the property that was set to undefined?


There's a difference between a property existing and being undefined and a property not existing, so Chrome is being sensible here. If you assign a value to a property then the property fundamentally exists in that object. One difference is that a property that has been explicitly set to be undefined will show up in a for...in loop:

var foo = {};
foo.bar = undefined;

// The following will alert "bar"
for (var i in foo) {
    alert(i);
}

Another is that "bar" in foo will return true, as will foo.hasOwnProperty("bar").


Technically, undefined is a valid value to assign to a variable. It does make a difference albeit usually not useful:

var foo = {
    bar: undefined
};

foo.hasOwnProperty("bar"); // returns true
foo.hasOwnProperty("bat"); // returns false

Also:

for (var n in foo) {
    console.log(n, foo[n]); // should log "bar" and "undefined"
}

I personally would follow the advise given by Crockford in this case. Assigning undefined as a value can lead to confusing code and should therefore be considered bad. It surprises people not expecting it.

We already have null to use for this purpose which is less confusing to future maintainers. Let undefined really mean not defined and use null to mean not known.

Remember that when reading Crockford's book you're reading advice on best practices and opinion on how javascript should work according to him. How javascript actually works is a different matter altogether (and according to him not necessarily good).


undefined is Javascript's way of telling you that a value doesn't exist instead of throwing an error when you access the property without a try/catch block. Although technically what Chrome is displaying is wrong by Crockford's account, it is at least logical; the property exists, albeit as undefined.

When you want to remove a property, you can use the delete operator:

delete foo.bar;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜