Skip to content

Commit 3eeb90b

Browse files
committed
docs(class): edit private method ruanyf#572
1 parent 0051af0 commit 3eeb90b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

docs/class.md

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,9 @@ class Foo {}
374374

375375
上面的代码不会报错,因为`Bar`继承`Foo`的时候,`Foo`已经有定义了。但是,如果存在`class`的提升,上面代码就会报错,因为`class`会被提升到代码头部,而`let`命令是不提升的,所以导致`Bar`继承`Foo`的时候,`Foo`还没有定义。
376376

377-
## 私有方法
377+
## 私有方法和私有属性
378+
379+
### 现有的方法
378380

379381
私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现。
380382

@@ -441,9 +443,9 @@ export default class myClass{
441443

442444
上面代码中,`bar``snaf`都是`Symbol`值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。
443445

444-
## 私有属性
446+
### 私有属性的提案
445447

446-
与私有方法一样,ES6 不支持私有属性。目前,有一个[提案](https://github.com/tc39/proposal-class-fields#private-fields),为`class`加了私有属性。方法是在属性名之前,使用`#`表示。
448+
与私有方法一样,ES6 不支持私有属性。目前,有一个[提案](https://github.com/tc39/proposal-private-methods),为`class`加了私有属性。方法是在属性名之前,使用`#`表示。
447449

448450
```javascript
449451
class Point {
@@ -485,6 +487,28 @@ class Foo {
485487
}
486488
```
487489

490+
上面代码中,`#sum()`就是一个私有方法。
491+
492+
另外,私有属性也可以设置 getter 和 setter 方法。
493+
494+
```javascript
495+
class Counter {
496+
#xValue = 0;
497+
498+
get #x() { return #xValue; }
499+
set #x(value) {
500+
this.#xValue = value;
501+
}
502+
503+
constructor() {
504+
super();
505+
// ...
506+
}
507+
}
508+
```
509+
510+
上面代码中,`#x`是一个私有属性,它的读写都通过`get #x()``set #x()`来完成。
511+
488512
## this 的指向
489513

490514
类的方法内部如果含有`this`,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

docs/reference.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@
185185
- Jake Archibald, [Async functions - making promises friendly](https://developers.google.com/web/fundamentals/getting-started/primers/async-functions)
186186
- Axel Rauschmayer, [ES proposal: asynchronous iteration](http://www.2ality.com/2016/10/asynchronous-iteration.html): 异步遍历器的详细介绍
187187
- 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 函数内部捕捉错误的方法
188+
- 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个好处
188189

189190
## Class
190191

0 commit comments

Comments
 (0)