2017-08-24 110 views
0

有人可以解释为什么这不起作用?检查typeOf undefined无法正常工作?

setOrientation: function() { 
    if (typeof oldOrientation !== 'undefined') console.log(oldOrientation); 
    let oldOrientation = orientation; 
    //other code 
} 

This throwbacks oldOrientation is undefined。我最终只是删除了let,它开始工作,但我很难完全理解为什么。我认为这与范围界定有关?

我已经通过在全球声明oldOrientation解决了这个问题,我只是想明白为什么typeof的比较没有按照原来的方式工作。

+0

因为你在函数内部定义它,使之成为全局函数。 – epascarello

+0

但不管怎么样,它不应该比较已经返回'“undefined”,因此不会出现错误? –

+3

吊装....... – epascarello

回答

3

From MDN let:

In ECMAScript 2015, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

意味着你使用的变量之前,它是定义。


如果你习惯使用var,会发生什么情况是var声明移到因为吊装块范围的顶部。所以,下面的函数

function foo() { 
    console.log(typeof bar) 
    var bar = "123"; 
} 

被视为

function foo() { 
    var bar; 
    console.log(typeof bar) 
    bar = "123"; 
} 

但是当你使用let,他们是没有提升,因此声明不被移至块的顶部。

+0

有一点帮助,但这是否意味着Chrome正在错误地处理错误? –

+0

我在chrome中运行它并得到''message“:”未捕获的ReferenceError:oldOrientation没有被定义“,所以看起来好像它正确地返回了错误消息。 – epascarello

+0

@epascarello javascript noob here,我来自c#,很难理解你在说什么。所以基本上问题是'let'没有使用变量提升,因此如果用'let'声明变量,那么if语句就没有意义了?但用'var'就可以了? – jdmdevdotnet

2

想象一下这样的简单情况:

let a = 1; 

{ 
alert(a); 
let a = 2; 
} 

然后警报(一)会做一个变量查找。这从当前范围(块)开始,它有自己的变量声明()但尚未设置(a = 2),因此其尚未定义。上等于:

let a = 1; 

{ 
let a /* = undefined */; 
alert(a); 
a = 2; 
} 

(即变量的声明被执行的代码被称为hoisting前...)

+2

这是一个很好的答案,你应该提及吊装,可能指向一个资源,以了解更多关于提升在JS –

+0

对不起,但您是否说因为提升,在比较时,变量*被声明,但是当它试图记录它时,它是未定义的? –

+0

@rather notsay是的。当一个变量被声明时,它的设置为undefined。 –