GithubHelp home page GithubHelp logo

Comments (7)

kflizongbao avatar kflizongbao commented on May 1, 2024 44

应该作用域的角度去解释,a是全局作用域,a函数内部自然找不到变量a,所以输出函数a

from fe-interview.

GolderBrother avatar GolderBrother commented on May 1, 2024 41

立即执行的函数表达式(IIFE)的函数名称跟内部变量名称重名后,函数名称优先,因为函数名称是不可改变的,内部会静默失败,在严格模式下会报错

var a = 1;
(function a () {
    'use strict';
    a = 2;
    console.log(a);
})();
 VM1059:4 Uncaught TypeError: Assignment to constant variable.
    at a (<anonymous>:4:7)
    at <anonymous>:6:3

from fe-interview.

Genzhen avatar Genzhen commented on May 1, 2024 17

答案

ƒ  a () {
      a = 2;
      console.log(a);
 }

解析
立即调用的函数表达式(IIFE) 有一个 自己独立的 作用域,如果函数名称与内部变量名称冲突,就会永远执行函数本身;所以上面的结果输出是函数本身;

from fe-interview.

SnailOwO avatar SnailOwO commented on May 1, 2024 3
1. 打印结果内容如下:
ƒ a() {
   a = 2;
   console.log(a)
}
2. 原因:

> 作用域可以理解为执行上下文中申明的变量和作用的范围;包括块级作用域/函数作用域;

> 变量提升:一个声明在函数体内都是可见的,**函数声明优先于变量声明;**

> 在非匿名自执行函数中,函数变量为只读状态无法修改;

from fe-interview.

cxs8462 avatar cxs8462 commented on May 1, 2024

受教了

from fe-interview.

MillionQW avatar MillionQW commented on May 1, 2024

这道用函数作用域解释比较合理? a 是在全局环境定义的,IIFE 执行的时候,先找当前作用域下有没有变量 a,此时 a 就是当前函数,所以不用继续往上一层作用于继续寻找了,所以打印了函数本身。
所以如果变量 a 是在 IIFE 里定义的话,就会输出新变量 a:

var a = 1;
(function a() {
 var a = 2;
 console.log(a)  // 2
})()

from fe-interview.

zhujianxiong avatar zhujianxiong commented on May 1, 2024

严格模式下会报错

为啥严格模式下会报错呢?

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.