mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 18:32:22 +00:00
docs(class): edit arrow function'this
This commit is contained in:
parent
6fc46035ce
commit
67eee047ee
@ -505,17 +505,18 @@ class Logger {
|
|||||||
另一种解决方法是使用箭头函数。
|
另一种解决方法是使用箭头函数。
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
class Logger {
|
class Obj {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.printName = (name = 'there') => {
|
this.getThis = () => this;
|
||||||
this.print(`Hello ${name}`);
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ...
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const myObj = new Obj();
|
||||||
|
myObj.getThis() === myObj // true
|
||||||
```
|
```
|
||||||
|
|
||||||
|
箭头函数内部的`this`总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以`this`会总是指向实例对象。
|
||||||
|
|
||||||
还有一种解决方法是使用`Proxy`,获取方法的时候,自动绑定`this`。
|
还有一种解决方法是使用`Proxy`,获取方法的时候,自动绑定`this`。
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
@ -94,6 +94,7 @@
|
|||||||
- Nicholas C. Zakas, [The ECMAScript 2016 change you probably don't know](https://www.nczonline.net/blog/2016/10/the-ecmascript-2016-change-you-probably-dont-know/): 使用参数默认值时,不能在函数内部显式开启严格模式
|
- Nicholas C. Zakas, [The ECMAScript 2016 change you probably don't know](https://www.nczonline.net/blog/2016/10/the-ecmascript-2016-change-you-probably-dont-know/): 使用参数默认值时,不能在函数内部显式开启严格模式
|
||||||
- Axel Rauschmayer, [ES proposal: optional catch binding](http://2ality.com/2017/08/optional-catch-binding.html)
|
- Axel Rauschmayer, [ES proposal: optional catch binding](http://2ality.com/2017/08/optional-catch-binding.html)
|
||||||
- Cynthia Lee, [When you should use ES6 arrow functions — and when you shouldn’t](https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26): 讨论箭头函数的适用场合
|
- Cynthia Lee, [When you should use ES6 arrow functions — and when you shouldn’t](https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26): 讨论箭头函数的适用场合
|
||||||
|
- Eric Elliott, [What is this?](https://medium.com/javascript-scene/what-is-this-the-inner-workings-of-javascript-objects-d397bfa0708a): 箭头函数内部的 this 的解释。
|
||||||
|
|
||||||
## 对象
|
## 对象
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user