Giter Site home page Giter Site logo

JS作用域和变量提升 about drx HOT 1 OPEN

axlroseart avatar axlroseart commented on September 11, 2024
JS作用域和变量提升

from drx.

Comments (1)

axlroseart avatar axlroseart commented on September 11, 2024

先写一个面试的时候可能会被面试官考的例子:

var x = 2
(function() {
 x = 4
 console.log(x)
})()

问执行这段代码之后会输出什么?

输出结果为:
image
刚开始可能会觉得答案有点出人意料,需要仔细观察和结合多个知识点才能很好的解释这个结果。
首先,我们应该都知道 (function() {})() 这是个自执行匿名函数,或者所谓的匿名包装器,也就是说这个函数会立即执行。然后再看这个函数内部,重新赋值x = 4,虽然函数外部定义的x = 2,但是在当前作用域(匿名函数内部)下,重新给x赋值为4,所以按理说会直接输出 数字 4 才对,但是为什么报错呢?
原因其实很简单,虽然我们平时写作通常会这么些,但是js代码在被解析的时候,并不会按照像“换行”这样的格式去解析,或者说叫切分,所以这部分代码会被解析成:

var x = 2(function() { ... })()

显而易见,2被误认为成了一个方法名,所以被认为是在执行方法'2',但2其实是个数字,所以才会报2 is not a function 的错。因此如果在2后面加上 ; 的时候,结果就完全不一样了,或者说就符合这段代码本身该有的亚子了:
image
像这种错误其实日常开发中稍微不注意就很容易出现,所以除了掌握js正常情况下的语法之外,还需要考虑运行情况下可能会出现的问题。

from drx.

Related Issues (15)

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.