来源:http://davidshariff.com/blog/javascripts-undefined-explored/
JavaScript’s Undefined Explored
(本文就是自己翻译一下)
关于JavaScript中undefined(未定义)变量类型的探索(探讨),听起来是一个简单的概念,不过你真的知道一个变量或者属性在 JavaScript中真正的存在方式?理解这个概念的最好方式是?怎样考虑到所有的(边缘)情况。首先,向我们看看什么是undefined...
Overview of undefined——未定义的概述
变量的值被赋予一个类型,就是JavaScript中的几个内置的本地类型:Undefined Null Boolean String Number Object Reference etc…注意undefined,这个内置类型Undefined ,只有一个简单的原始值,叫做 undefined 。每当你定义一个变量时,它就被分配为undefined,直到您以编程方式赋予它不同的值时
这里有3种未定义的表现形式:
var foo,
bar=(function(){ // do some stuff }()),
baz=(function(){
var hello;
return hello;
}());
typeof foo; // undefined
typeof bar; // undefined
typeof baz; // undefined
foo === undefined;//true
在低版本的浏览器中:undefined 可以被重新定义,高版本则不行(ECMA 5
的规定),例如
typeof undefined; // undefined
undefined=99;
typeof undefined; // number
看下面的例子:
null == undefined // true
null !== undefined // true
这说明null 和undefined 都可以强制转换为 0;
在object中 undefined的属性
var foo={};
foo.bar; // undefined
foo.bar(); // TypeError
如果 未定义的属性 想变成函数时,就会报错(类型错误)
这时可以使用in运算符检查对象中是否存在某种属性:
var foo = {};
// undefined (Not good, bar has never been declared in the window object)
typeof foo.bar;
// false (如果你不在意原型链,可以这样用)
'bar' in foo;
// false (use this if you do care about the prototype chain)
foo.hasOwnProperty('bar');
你应该使用typeof还是in / hasOwnProperty?
通常情况下,typeof用于检查属性的值;而 in/hasOwnProperty用于检查属性是否存在
Let’s recap with some examples(举几个例子)
检查变量是否存在
if(type of foo!=='undefined'){}
检查一个对象 是否存在某种属性,而不管属性是否被赋值
// exists on the object, checks the prototype too
if('foo' in bar){}
// exists directly on the object, don't check the prototype
if(bar.hasOwnProperty('foo')){}
检查一个对象 是否存在某种属性,同时存在属性值。
var bar={foo:false};
if('foo' in bar && typeof bar.foo!=='undefined'){
// bar.foo exists, and it contains a value which was programatically assigned
}
网友评论