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

藏在 JS 中的细节笔记 #10

Open
XueSeason opened this issue Jul 2, 2016 · 0 comments
Open

藏在 JS 中的细节笔记 #10

XueSeason opened this issue Jul 2, 2016 · 0 comments

Comments

@XueSeason
Copy link
Member

XueSeason commented Jul 2, 2016

本文将持续更新。收录平时学习中发现的细节。

Day 2016/7/2

今天重新过一遍 ES2015 的语法,准备研究通过 Babel 转换后的 ES5 的语法实现。

// ES2015 代码
{
  a = 1;
  let a;
}
console.log(a);
// 转换后
"use strict";
{
  _a = 1;
  var _a = void 0;
}
console.log(a);

我们可以看出这里 let 块级作用域的实现形式,同时测试了下 let 转换后是如何避免变量提升的。
void 0 就是今天的主题。

这里 void 是一个操作符。

查阅 MDN 相关链接,是这么描述的:

The void operator evaluates the given expression and then returns undefined.

void 操作符计算给定的表达式,然后返回undefined

过去我们用到最多的地方是在一个标签中插入 javascript: URI ,例如:

<a href="javascript:void(0);">
  这个链接点击之后不会做任何事情,如果去掉 void(),
  点击之后整个页面会被替换成一个字符 0。
</a>

<a href="javascript:void(document.body.style.backgroundColor='green');">
  点击这个链接会让页面背景变成绿色。
</a>

以下是 MDN 的解释:
当用户点击一个以 javascript: URI 时,浏览器会对冒号后面的代码进行求值,然后把求值的结果显示在页面上,这时页面基本上是一大片空白,这通常不是我们想要的。只有当这段代码的求值结果是 undefined 的时候,浏览器才不会去做这件傻事,所以我们经常会用 void 运算符来实现这个需求。

void 0 最终都会返回一个 undefined,那么我们为什么不直接用 undefined ?
面向 Google + StackOverflow 编程,我们找到这样的答案:

void, on the other hand, cannot be overidden. void 0 will always return undefined. 
undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

以及

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. 
The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

参考链接

第一段话,说的是在老版本浏览器中 undefined 很可能被覆盖,造成后续的变量被赋值为 undefined 不是预期的结果,而使用 void 0 可以总是返回 undefined 的原值。

第二段话,说的是在现代浏览器中 void 0 依然有用武之地,void 0 比 undifined 少很多字节,这样不仅在日常书写中很方便,同时在网络传输中可以减少带宽。

差不多就这些了。

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

No branches or pull requests

1 participant