Comments (1)
先写一个面试的时候可能会被面试官考的例子:
var x = 2
(function() {
x = 4
console.log(x)
})()
问执行这段代码之后会输出什么?
输出结果为:
刚开始可能会觉得答案有点出人意料,需要仔细观察和结合多个知识点才能很好的解释这个结果。
首先,我们应该都知道 (function() {})() 这是个自执行匿名函数,或者所谓的匿名包装器,也就是说这个函数会立即执行。然后再看这个函数内部,重新赋值x = 4,虽然函数外部定义的x = 2,但是在当前作用域(匿名函数内部)下,重新给x赋值为4,所以按理说会直接输出 数字 4 才对,但是为什么报错呢?
原因其实很简单,虽然我们平时写作通常会这么些,但是js代码在被解析的时候,并不会按照像“换行”这样的格式去解析,或者说叫切分,所以这部分代码会被解析成:
var x = 2(function() { ... })()
显而易见,2被误认为成了一个方法名,所以被认为是在执行方法'2',但2其实是个数字,所以才会报2 is not a function 的错。因此如果在2后面加上 ; 的时候,结果就完全不一样了,或者说就符合这段代码本身该有的亚子了:
像这种错误其实日常开发中稍微不注意就很容易出现,所以除了掌握js正常情况下的语法之外,还需要考虑运行情况下可能会出现的问题。
from drx.
Related Issues (15)
- 深入了解js拷贝(赋值与引用)
- 深入了解VUE
- React-Native - 知识收集整理 HOT 1
- JS原型链与继承相关 HOT 6
- 服务端渲染
- 开发中比较实用的JS技巧类 HOT 6
- ES6 新特性相关
- 算法与数据结构
- JS基础算法相关(数组,字符串处理等)
- 微信小程序使用总结 HOT 1
- 混合web app开发相关手记 HOT 12
- 面试相关 HOT 2
- React开发手记 HOT 1
- Typescript相关 HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from drx.