Skip to content

Commit f21e959

Browse files
committed
fix Symbol desc for doc updates.
1 parent 355f0af commit f21e959

File tree

1 file changed

+54
-10
lines changed

1 file changed

+54
-10
lines changed

README_zhCn.md

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -629,22 +629,66 @@ class Personal extends Person {
629629

630630
## Symbols
631631

632-
符号在ES6版本之前就已经存在了,但现在我们拥有一个公共的接口来直接使用它们。
633-
下面的例子是创建了两个永远不会冲突的属性。
632+
符号(Symbols)在ES6版本之前就已经存在了,但现在我们拥有一个公共的接口来直接使用它们。
633+
Symbols对象是一旦创建就不可以被更改的(immutable)而且能被用做hash数据类型中的键。
634+
635+
### Symbol( )
636+
调用 `Symbol()` 或者 `Symbol(描述文本)` 会创建一个唯一的、在全局中不可以访问的符号对象。
637+
一个 `Symbol()` 的应用场景是:在自己的项目中使用第三方代码库,且你需要给他们的对象或者命名空间打补丁代码,又不想改动或升级第三方原有代码的时候。
638+
举个例子,如果你想给 `React.Component` 这个类添加一个 `refreshComponent` 方法,但又确定不了这个方法会不会在下个版本中加入,你可以这么做:
634639

635640
```javascript
636-
const key = Symbol();
637-
const keyTwo = Symbol();
638-
const object = {};
641+
const refreshComponent = Symbol();
642+
643+
React.Component.prototype[refreshComponent] = () => {
644+
// do something
645+
}
646+
```
647+
648+
### Symbol.for(key)
649+
650+
使用 `Symbol.for(key)` 也是会创建一个不可改变的Symbol对象,但区别于上面的创建方法,这个对象是在全局中可以被访问到的。
651+
调用两次 `Symbol.for(key)` 会返回相同的Symbol实例。
639652

640-
object[key] = 'Such magic.';
641-
object[keyTwo] = 'Much Uniqueness';
653+
**提示**:这并不同于 `Symbol(description)`
642654

643-
// Two Symbols will never have the same value
644-
>> key === keyTwo
645-
>> false
655+
```javascript
656+
Symbol('foo') === Symbol('foo') // false
657+
Symbol.for('foo') === Symbol('foo') // false
658+
Symbol.for('foo') === Symbol.for('foo') // true
646659
```
647660

661+
一个Symbols常用的使用场景,是需要使用特别 `Symbol.for(key)` 方法来实现代码间的协作。
662+
这能让你在你的代码中,查找包含已知的接口的第三方代码中Symbol成员。(译者:这句话好难翻。。。原文:This can be
663+
achieved by having your code look for a Symbol member on object arguments from third parties that contain some known interface. )举个例子:
664+
665+
```javascript
666+
function reader(obj) {
667+
const specialRead = Symbol.for('specialRead');
668+
if (obj[specialRead]) {
669+
const reader = obj[specialRead]();
670+
// do something with reader
671+
} else {
672+
throw new TypeError('object cannot be read');
673+
}
674+
}
675+
```
676+
677+
之后在另一个库中:
678+
679+
```javascript
680+
const specialRead = Symbol.for('specialRead');
681+
682+
class SomeReadableType {
683+
[specialRead]() {
684+
const reader = createSomeReaderFrom(this);
685+
return reader;
686+
}
687+
}
688+
```
689+
690+
> **注意**`Symbol.iterable` 在ES6中像其他可枚举的对象,如数组,字符串,generators一样,当这个方法被调用时会激活一个枚举器并返回一个对象。
691+
648692
<sup>[(回到目录)](#table-of-contents)</sup>
649693

650694
## Maps

0 commit comments

Comments
 (0)