Chicken first or egg?

本文探讨了JavaScript中函数声明与变量声明的区别,解释了为什么某些代码会导致不同的执行结果,并对比了函数声明与函数表达式的执行时机差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Let’s look at the following code:

<script>
    foo();//execute function foo
    function foo()
    {
        console.log("execute function foo");
    }
    console.log(a);//undefined 
    var a=1;
</script>

Can you see the difference?Why they lead to different results?
In fact,function and variable declaration executed during the compilation before runtime.
The code above will execute like this:

<script>
    function foo()
    {
        console.log("execute function foo");
    }
    var a;
    foo();//execute function foo
    console.log(a);//undefined 
    a=1;
</script>

Each declaration will execute first in its own scope before run.

<script>
    foo();
    function foo()
    {
        console.log(a);//undefined
        var a=1;
    }
</script>

However,function expression does not work like function declaration.

<script>
    foo();//TypeError: foo is not a function
    var foo=function()
    {
        console.log("foo()");
    }
</script>

It likes

<script>
    foo();//TypeError: foo is not a function
    var foo;
</script>

Tips:If you write more than one same function,the behind covers the front.

<script>
    foo();//2
    function foo()
    {
        console.log("1");
    }

    function foo()
    {
        console.log("2");
    }
</script>

Q:fill in the blanks with the correct answers:

<script>
    var foo=function()
    {
        console.log("1");
    }
    foo();//①
    var foo=function()
    {
        console.log("2");
    }
    foo();//②
</script>
<script>
    function foo()
    {
        console.log("1");
    }
    foo();//③
    var foo=function()
    {
        console.log("2");
    }
    foo();//④
    function foo()
    {
        console.log("3");
    }
    foo();//⑤
</script>

A: [1,2,3,2,2].

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值