Skip to content
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

feat: use const variables insteadof function parameters #90

Merged
merged 3 commits into from
Mar 29, 2023

Conversation

kuitos
Copy link
Owner

@kuitos kuitos commented Mar 29, 2023

之前的函数参数方式存在缺陷,比如这样一段代码:

const obj = { a: 123 }
with(obj) {
  var a = typeof a === 'number' ? a : 456;
  console.log(a); // 123
}

如果换成函数包一层的话:

const obj = { a: 123 }
with(obj) {
  (function(){
    var a = typeof a === 'number' ? a : 456;
    console.log(a); // 456
  })()
}

两者执行结果是有差异的,原因是 function 是独立作用域,此时 a 变量是当前作用域独立的变量,而其初始值就是 undefined,但是在 with 上下文中,因为 obj 中存在同名 a,所以 with 的词法作用域中不会新建变量 a,而是会直接读 obj.a。

背后的原理是 https://www.yuque.com/kuitos/gky7yw/mhfzh7

// 将 scopedGlobalVariables 拼接成函数声明,用于缓存全局变量,避免每次使用时都走一遍代理
const scopedGlobalVariableFnParameters = scopedGlobalVariables.length ? scopedGlobalVariables.join(',') : '';
// 将 scopedGlobalVariables 拼接成变量声明,用于缓存全局变量,避免每次使用时都走一遍代理
const scopedGlobalVariableDefinition = scopedGlobalVariables.length ? `const {${scopedGlobalVariables.join(',')}}=this;` : ''
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里是不是应该要改成var。
比如,我这儿打包后的产物里有:var window = typeof window == "object" ? window : {};
就会报错:Uncaught SyntaxError: Identifier 'window' has already been declared (at......

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

改成 var 性能优化就失效了,原理可以看下 pr conversation 里的文档链接

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不过这个确实会导致你的问题,不太好解

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants