var 声明变量

157 阅读1分钟

var 声明变量

函数内部声明变量

/**
 * QQ群:976961880
 * 函数内部声明变量,未使用var声明,那么变量会成为全局变量
 * 函数执行之后,message1会成为全局变量
 */
function test1() {
    message1 = '跃码教育'
}
test1()
console.log(message1) //跃码教育

ps:错误示例

函数内部未使用var声明

function test1() {
    message1 = '跃码教育'
}
// 函数内部声明变量,未使用var声明,那么变量会成为全局变量
// 函数执行之后,message1会成为全局变量
test1()
console.log(message1) //跃码教育

函数内部先使用,后用var声明

function test2() {
    console.log(auth)
    var auth = '跃码教育'
}
// 在函数内部通过关键字var声明的变量会提升到函数作用域顶部
// test2和test3等价
test2() //undefined

等价示例

function test3() {
    var auth
    console.log(auth)
    auth = '跃码教育'
}
// test2和test3等价
test3() //undefined