1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-27 20:32:21 +00:00

docs(let): ES6的块级作用域使得函数可以在条件作用域内声明

This commit is contained in:
ruanyf 2016-03-05 14:35:33 +08:00
parent f50a775466
commit 1ae51bdea5
2 changed files with 39 additions and 9 deletions

View File

@ -887,13 +887,6 @@ function foo() {
}
// ES5
function foo() {
setTimeout(function () {
console.log("id:", this.id);
}.bind(this), 100);
}
// 或者
function foo() {
var _this = this;
@ -903,6 +896,8 @@ function foo() {
}
```
上面代码中箭头函数转成ES5代码时内部的`this`需要改为引用外部的`this`
请问下面的代码之中有几个`this`
```javascript
@ -910,7 +905,7 @@ function foo() {
return () => {
return () => {
return () => {
console.log("id:", this.id);
console.log(`id:`, this.id);
};
};
};

View File

@ -310,7 +310,42 @@ let f;
f() // "secret"
```
需要注意的是如果在严格模式下函数只能在顶层作用域和函数内声明其他情况比如if代码块、循环代码块的声明都会报错。
ES5的严格模式规定函数只能在顶层作用域和函数内声明其他情况比如if代码块、循环代码块的声明都会报错。
```javascript
// ES5
'use strict';
if (true) {
function f() {} // 报错
}
```
ES6由于引入了块级作用域这种情况可以理解成函数在块级作用域内声明因此不报错但是构成区块的大括号不能少否则还是会报错。
```javascript
// 不报错
'use strict';
if (true) {
function f() {}
}
// 报错
'use strict';
if (true)
function f() {}
```
另外,这样声明的函数,在区块外是不可用的。
```javascript
'use strict';
if (true) {
function f() {}
}
f() // ReferenceError: f is not defined
```
上面代码中,函数`f`是在块级作用域内部声明的,外部是不可用的。
## const命令