diff --git a/docs/class.md b/docs/class.md index e31c317..ba4d637 100644 --- a/docs/class.md +++ b/docs/class.md @@ -505,17 +505,18 @@ class Logger { 另一种解决方法是使用箭头函数。 ```javascript -class Logger { +class Obj { constructor() { - this.printName = (name = 'there') => { - this.print(`Hello ${name}`); - }; + this.getThis = () => this; } - - // ... } + +const myObj = new Obj(); +myObj.getThis() === myObj // true ``` +箭头函数内部的`this`总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以`this`会总是指向实例对象。 + 还有一种解决方法是使用`Proxy`,获取方法的时候,自动绑定`this`。 ```javascript diff --git a/docs/reference.md b/docs/reference.md index a2a989f..d08968b 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -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/): 使用参数默认值时,不能在函数内部显式开启严格模式 - 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): 讨论箭头函数的适用场合 +- Eric Elliott, [What is this?](https://medium.com/javascript-scene/what-is-this-the-inner-workings-of-javascript-objects-d397bfa0708a): 箭头函数内部的 this 的解释。 ## 对象