变量声明
下文是JavaScript中声明变量的不同方法。
注释与console.log
足够说明这里发生了什么:
var y, x = y = 1 //== var x; var y; x = y = 1
console.log('--> 1:', `x = ${x}, y = ${y}`)
// 将会输出
//--> 1: x = 1, y = 1
首先,我们只设置了两个变量。并没有很多。
;(() => {
var x = y = 2 // == var x; y = 2;
console.log('2.0:', `x = ${x}, y = ${y}`)
})()
console.log('--> 2.1:', `x = ${x}, y = ${y}`)
// 将会输出
//2.0: x = 2, y = 2
//--> 2.1: x = 1, y = 2
正如你所看到的,代码只改变了全局的y
,因为我们在闭包里并没有声明此变量。
;(() => {
var x, y = 3 // == var x; var y = 3;
console.log('3.0:', `x = ${x}, y = ${y}`)
})()
console.log('--> 3.1:', `x = ${x}, y = ${y}`)
// 将会输出
//3.0: x = undefined, y = 3
//--> 3.1: x = 1, y = 2
现在我们用var
声明了两个变量。意味着他们仅在闭包内有作用。
;(() => {
var y, x = y = 4 // == var x; var y; x = y = 4
console.log('4.0:', `x = ${x}, y = ${y}`)
})()
console.log('--> 4.1:', `x = ${x}, y = ${y}`)
// 将会输出
//4.0: x = 4, y = 4
//--> 4.1: x = 1, y = 2
两个变量都使用var
声明了而且在之后又给它们赋值。由于local > global
,闭包内声明了x
和y
,意味着闭包内是无法访问全局的x
和y
的。
x = 5 // == x = 5
console.log('--> 5:', `x = ${x}, y = ${y}`)
// 将会输出
//--> 5: x = 5, y = 2
最后一行的结果是很明显的。
你可以在这里测试并看到结果 感谢babel.
更多相关内容请看MDN.
特别感谢@kurtextrem的合作 :)!
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW