Skip to content

变量作用域,闭包一节的任务,答案错误❌ #1186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
shylock-wu opened this issue Jan 11, 2024 · 5 comments
Closed

变量作用域,闭包一节的任务,答案错误❌ #1186

shylock-wu opened this issue Jan 11, 2024 · 5 comments
Labels
Solved Problem solved

Comments

@shylock-wu
Copy link

位置

image

网站实际运行效果

image

浏览器控制台运行效果

image

结论

所以我感觉实际上sayHi函数已经被提升了,并且新的词法环境使得两个变量都是能够访问到的

@shylock-wu
Copy link
Author

贴个链接

@7ASSEL
Copy link

7ASSEL commented Mar 27, 2024

+1,我这边试了也是正常

@songhn233
Copy link
Member

@shylock-wu @7ASSEL Hello,这个实际是因为 devtool 默认在非严格模式下,详见 https://zh.javascript.info/strict-mode

image

另外,在现代前端开发工具链下,预置开发环境和构建工具基本都会默认开启严格模式。除非显式的通过 @babel/plugin-transform-strict-mode 或者一些配置来放开限制(不建议),非严格模式主要为了向前兼容 ES5 之前的一些表现。

image

@shylock-wu
Copy link
Author

shylock-wu commented Jun 9, 2024

@songhn233 Hi 我测试了一下,在严格模式下,例如在NodeJS中执行这种js文件,是会报错的。但是在Chrome浏览器的控制台执行

"use strict";
let phrase = "Hello";

if (true) {
  let user = "John";

  function sayHi() {
    alert(`${phrase}, ${user}`);
  }
}

sayHi();

还是会正常alert,即使是已经写了use strict,很奇怪。参考下面的图片
CleanShot 2024-06-09 at 15 30 29
CleanShot 2024-06-09 at 15 30 04

@songhn233
Copy link
Member

但是在Chrome浏览器的控制台执行
还是会正常alert,即使是已经写了use strict,很奇怪。参考下面的图片

@shylock-wu 可以试一下重新打开 devtool 后直接执行包含 "use strict" 的代码块,就会提示 Uncaught ReferenceError: sayHi is not defined 了。

这是因为截图中其实执行了两次,第一次在非严格模式下,sayHi 已经在全局上下文下被创建了。第二次虽然在严格模式,但 sayHi 在全局可以被找到,alert 就还是正常处理了。每个代码块之间是不会隔离的,需要重启 devtool 来清除副作用。

@leviding leviding added the Solved Problem solved label Jun 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Solved Problem solved
Projects
None yet
Development

No branches or pull requests

4 participants