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
+3 -8
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);
};
};
};
+36 -1
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命令