欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

变量提升与匿名函数

程序员文章站 2022-03-08 23:28:16
...

 a存在变量提升,所以a等于undefined

var a = 1;
let b = 4;
(function() {
    console.log(a);//undefined
    var a = 3;
    let b = 4;
    console.log(a, b);//3,4
})()
var a = 1;
let b = 4;

function try1() {
    var a = 3;
    console.log(a);//undefined
    let b = 4;
    console.log(a, b);//3,4
};
try1()

 作用域内未定义a

var a = 1;
let b = 4;
(function() {
    console.log(a); //1
    let b = 4;
    console.log(a, b); //3,4
})()
var a = 1;
let b = 4;

function try1() {
    console.log(a); //1
    let b = 4;
    console.log(a, b); //3,4
};
try1()

 b不存在变量提升,所以报错

var a = 1;
let b = 4;
(function() {
    console.log(a, b);
    var a = 3;
    let b = 4;
    console.log(a, b);
})()
//报错
var a = 1;
let b = 4;
(function() {
    var a = 3;
    console.log(a, b);
    let b = 4;
    console.log(a, b);
})()
//报错

特殊情况

var a;
let b = 4;
function try1() {
    console.log(a); //undefined
    let b = 4;
    console.log(a, b); //undefined,4
};
try1()
a = 1

匿名函数可以拆成一个函数定义和一个函数执行,函数定义会提升,函数执行保持原来位置

例如:

var name = '小吴同学';
(function() {
    if (typeof name === "undefined") {
        name = '小邵先生';
        console.log('第一次' + name);
    } else {
        console.log('第二次' + name);
    }
    console.log(name);
})()
// 第二次小吴同学
var name = '小吴同学';
(function() {
    if (typeof name === "undefined") {
        var name = '小邵先生';
        console.log('第一次' + name);
    } else {
        console.log('第二次' + name);
    }
    console.log(name);
})()
//第一次小邵先生

相关标签: js javascript