From 3eeb90b85c9f770376b9e12142282b1b749caa3c Mon Sep 17 00:00:00 2001 From: ruanyf Date: Tue, 2 Jan 2018 17:29:38 +0800 Subject: [PATCH] docs(class): edit private method #572 --- docs/class.md | 30 +++++++++++++++++++++++++++--- docs/reference.md | 1 + 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/class.md b/docs/class.md index 927a38e..f3171c5 100644 --- a/docs/class.md +++ b/docs/class.md @@ -374,7 +374,9 @@ class Foo {} 上面的代码不会报错,因为`Bar`继承`Foo`的时候,`Foo`已经有定义了。但是,如果存在`class`的提升,上面代码就会报错,因为`class`会被提升到代码头部,而`let`命令是不提升的,所以导致`Bar`继承`Foo`的时候,`Foo`还没有定义。 -## 私有方法 +## 私有方法和私有属性 + +### 现有的方法 私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现。 @@ -441,9 +443,9 @@ export default class myClass{ 上面代码中,`bar`和`snaf`都是`Symbol`值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。 -## 私有属性 +### 私有属性的提案 -与私有方法一样,ES6 不支持私有属性。目前,有一个[提案](https://github.com/tc39/proposal-class-fields#private-fields),为`class`加了私有属性。方法是在属性名之前,使用`#`表示。 +与私有方法一样,ES6 不支持私有属性。目前,有一个[提案](https://github.com/tc39/proposal-private-methods),为`class`加了私有属性。方法是在属性名之前,使用`#`表示。 ```javascript class Point { @@ -485,6 +487,28 @@ class Foo { } ``` +上面代码中,`#sum()`就是一个私有方法。 + +另外,私有属性也可以设置 getter 和 setter 方法。 + +```javascript +class Counter { + #xValue = 0; + + get #x() { return #xValue; } + set #x(value) { + this.#xValue = value; + } + + constructor() { + super(); + // ... + } +} +``` + +上面代码中,`#x`是一个私有属性,它的读写都通过`get #x()`和`set #x()`来完成。 + ## this 的指向 类的方法内部如果含有`this`,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。 diff --git a/docs/reference.md b/docs/reference.md index a1878dc..a60a388 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -185,6 +185,7 @@ - Jake Archibald, [Async functions - making promises friendly](https://developers.google.com/web/fundamentals/getting-started/primers/async-functions) - Axel Rauschmayer, [ES proposal: asynchronous iteration](http://www.2ality.com/2016/10/asynchronous-iteration.html): 异步遍历器的详细介绍 - Dima Grossman, [How to write async await without try-catch blocks in Javascript](http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/): 除了 try/catch 以外的 async 函数内部捕捉错误的方法 +- Mostafa Gaafa, [6 Reasons Why JavaScript’s Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9): Async 函数的6个好处 ## Class