mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-28 21:32:20 +00:00
docs(let): ES6的块级作用域使得函数可以在条件作用域内声明
This commit is contained in:
parent
f50a775466
commit
1ae51bdea5
@ -887,13 +887,6 @@ function foo() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ES5
|
// ES5
|
||||||
function foo() {
|
|
||||||
setTimeout(function () {
|
|
||||||
console.log("id:", this.id);
|
|
||||||
}.bind(this), 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 或者
|
|
||||||
function foo() {
|
function foo() {
|
||||||
var _this = this;
|
var _this = this;
|
||||||
|
|
||||||
@ -903,6 +896,8 @@ function foo() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
上面代码中,箭头函数转成ES5代码时,内部的`this`需要改为引用外部的`this`。
|
||||||
|
|
||||||
请问下面的代码之中有几个`this`?
|
请问下面的代码之中有几个`this`?
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
@ -910,7 +905,7 @@ function foo() {
|
|||||||
return () => {
|
return () => {
|
||||||
return () => {
|
return () => {
|
||||||
return () => {
|
return () => {
|
||||||
console.log("id:", this.id);
|
console.log(`id:`, this.id);
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
37
docs/let.md
37
docs/let.md
@ -310,7 +310,42 @@ let f;
|
|||||||
f() // "secret"
|
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命令
|
## const命令
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user