File tree Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Original file line number Diff line number Diff line change @@ -374,7 +374,9 @@ class Foo {}
374
374
375
375
上面的代码不会报错,因为` Bar ` 继承` Foo ` 的时候,` Foo ` 已经有定义了。但是,如果存在` class ` 的提升,上面代码就会报错,因为` class ` 会被提升到代码头部,而` let ` 命令是不提升的,所以导致` Bar ` 继承` Foo ` 的时候,` Foo ` 还没有定义。
376
376
377
- ## 私有方法
377
+ ## 私有方法和私有属性
378
+
379
+ ### 现有的方法
378
380
379
381
私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现。
380
382
@@ -441,9 +443,9 @@ export default class myClass{
441
443
442
444
上面代码中,` bar ` 和` snaf ` 都是` Symbol ` 值,导致第三方无法获取到它们,因此达到了私有方法和私有属性的效果。
443
445
444
- ## 私有属性
446
+ ### 私有属性的提案
445
447
446
- 与私有方法一样,ES6 不支持私有属性。目前,有一个[ 提案] ( https://github.com/tc39/proposal-class-fields# private-fields ) ,为` class ` 加了私有属性。方法是在属性名之前,使用` # ` 表示。
448
+ 与私有方法一样,ES6 不支持私有属性。目前,有一个[ 提案] ( https://github.com/tc39/proposal-private-methods ) ,为` class ` 加了私有属性。方法是在属性名之前,使用` # ` 表示。
447
449
448
450
``` javascript
449
451
class Point {
@@ -485,6 +487,28 @@ class Foo {
485
487
}
486
488
```
487
489
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
+
488
512
## this 的指向
489
513
490
514
类的方法内部如果含有` this ` ,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
Original file line number Diff line number Diff line change 185
185
- Jake Archibald, [ Async functions - making promises friendly] ( https://developers.google.com/web/fundamentals/getting-started/primers/async-functions )
186
186
- Axel Rauschmayer, [ ES proposal: asynchronous iteration] ( http://www.2ality.com/2016/10/asynchronous-iteration.html ) : 异步遍历器的详细介绍
187
187
- 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个好处
188
189
189
190
## Class
190
191
You can’t perform that action at this time.
0 commit comments