内置的 Symbol 值

除了定义自己使用的 Symbol 值以外,ES6 还提供了 11 个内置的 Symbol 值,指向语言内部使用的方法。

Symbol.hasInstance

对象的Symbol.hasInstance属性,指向一个内部方法。当其他对象使用instanceof运算符,判断是否为该对象的实例时,会调用这个方法。比如,foo instanceof Foo在语言内部,实际调用的是Foo[Symbol.hasInstance](foo)

  1. class MyClass {
  2. [Symbol.hasInstance](foo) {
  3. return foo instanceof Array;
  4. }
  5. }
  6. [1, 2, 3] instanceof new MyClass() // true

上面代码中,MyClass是一个类,new MyClass()会返回一个实例。该实例的Symbol.hasInstance方法,会在进行instanceof运算时自动调用,判断左侧的运算子是否为Array的实例。

下面是另一个例子。

  1. class Even {
  2. static [Symbol.hasInstance](obj) {
  3. return Number(obj) % 2 === 0;
  4. }
  5. }
  6. // 等同于
  7. const Even = {
  8. [Symbol.hasInstance](obj) {
  9. return Number(obj) % 2 === 0;
  10. }
  11. };
  12. 1 instanceof Even // false
  13. 2 instanceof Even // true
  14. 12345 instanceof Even // false

Symbol.isConcatSpreadable

对象的Symbol.isConcatSpreadable属性等于一个布尔值,表示该对象用于Array.prototype.concat()时,是否可以展开。

  1. let arr1 = ['c', 'd'];
  2. ['a', 'b'].concat(arr1, 'e') // ['a', 'b', 'c', 'd', 'e']
  3. arr1[Symbol.isConcatSpreadable] // undefined
  4. let arr2 = ['c', 'd'];
  5. arr2[Symbol.isConcatSpreadable] = false;
  6. ['a', 'b'].concat(arr2, 'e') // ['a', 'b', ['c','d'], 'e']

上面代码说明,数组的默认行为是可以展开,Symbol.isConcatSpreadable默认等于undefined。该属性等于true时,也有展开的效果。

类似数组的对象正好相反,默认不展开。它的Symbol.isConcatSpreadable属性设为true,才可以展开。

  1. let obj = {length: 2, 0: 'c', 1: 'd'};
  2. ['a', 'b'].concat(obj, 'e') // ['a', 'b', obj, 'e']
  3. obj[Symbol.isConcatSpreadable] = true;
  4. ['a', 'b'].concat(obj, 'e') // ['a', 'b', 'c', 'd', 'e']

Symbol.isConcatSpreadable属性也可以定义在类里面。

  1. class A1 extends Array {
  2. constructor(args) {
  3. super(args);
  4. this[Symbol.isConcatSpreadable] = true;
  5. }
  6. }
  7. class A2 extends Array {
  8. constructor(args) {
  9. super(args);
  10. }
  11. get [Symbol.isConcatSpreadable] () {
  12. return false;
  13. }
  14. }
  15. let a1 = new A1();
  16. a1[0] = 3;
  17. a1[1] = 4;
  18. let a2 = new A2();
  19. a2[0] = 5;
  20. a2[1] = 6;
  21. [1, 2].concat(a1).concat(a2)
  22. // [1, 2, 3, 4, [5, 6]]

上面代码中,类A1是可展开的,类A2是不可展开的,所以使用concat时有不一样的结果。

注意,Symbol.isConcatSpreadable的位置差异,A1是定义在实例上,A2是定义在类本身,效果相同。

Symbol.species

对象的Symbol.species属性,指向一个构造函数。创建衍生对象时,会使用该属性。

  1. class MyArray extends Array {
  2. }
  3. const a = new MyArray(1, 2, 3);
  4. const b = a.map(x => x);
  5. const c = a.filter(x => x > 1);
  6. b instanceof MyArray // true
  7. c instanceof MyArray // true

上面代码中,子类MyArray继承了父类ArrayaMyArray的实例,bca的衍生对象。你可能会认为,bc都是调用数组方法生成的,所以应该是数组(Array的实例),但实际上它们也是MyArray的实例。

Symbol.species属性就是为了解决这个问题而提供的。现在,我们可以为MyArray设置Symbol.species属性。

  1. class MyArray extends Array {
  2. static get [Symbol.species]() { return Array; }
  3. }

上面代码中,由于定义了Symbol.species属性,创建衍生对象时就会使用这个属性返回的函数,作为构造函数。这个例子也说明,定义Symbol.species属性要采用get取值器。默认的Symbol.species属性等同于下面的写法。

  1. static get [Symbol.species]() {
  2. return this;
  3. }

现在,再来看前面的例子。

  1. class MyArray extends Array {
  2. static get [Symbol.species]() { return Array; }
  3. }
  4. const a = new MyArray();
  5. const b = a.map(x => x);
  6. b instanceof MyArray // false
  7. b instanceof Array // true

上面代码中,a.map(x => x)生成的衍生对象,就不是MyArray的实例,而直接就是Array的实例。

再看一个例子。

  1. class T1 extends Promise {
  2. }
  3. class T2 extends Promise {
  4. static get [Symbol.species]() {
  5. return Promise;
  6. }
  7. }
  8. new T1(r => r()).then(v => v) instanceof T1 // true
  9. new T2(r => r()).then(v => v) instanceof T2 // false

上面代码中,T2定义了Symbol.species属性,T1没有。结果就导致了创建衍生对象时(then方法),T1调用的是自身的构造方法,而T2调用的是Promise的构造方法。

总之,Symbol.species的作用在于,实例对象在运行过程中,需要再次调用自身的构造函数时,会调用该属性指定的构造函数。它主要的用途是,有些类库是在基类的基础上修改的,那么子类使用继承的方法时,作者可能希望返回基类的实例,而不是子类的实例。

Symbol.match

对象的Symbol.match属性,指向一个函数。当执行str.match(myObject)时,如果该属性存在,会调用它,返回该方法的返回值。

  1. String.prototype.match(regexp)
  2. // 等同于
  3. regexp[Symbol.match](this)
  4. class MyMatcher {
  5. [Symbol.match](string) {
  6. return 'hello world'.indexOf(string);
  7. }
  8. }
  9. 'e'.match(new MyMatcher()) // 1

Symbol.replace

对象的Symbol.replace属性,指向一个方法,当该对象被String.prototype.replace方法调用时,会返回该方法的返回值。

  1. String.prototype.replace(searchValue, replaceValue)
  2. // 等同于
  3. searchValue[Symbol.replace](this, replaceValue)

下面是一个例子。

  1. const x = {};
  2. x[Symbol.replace] = (...s) => console.log(s);
  3. 'Hello'.replace(x, 'World') // ["Hello", "World"]

Symbol.replace方法会收到两个参数,第一个参数是replace方法正在作用的对象,上面例子是Hello,第二个参数是替换后的值,上面例子是World

Symbol.search

对象的Symbol.search属性,指向一个方法,当该对象被String.prototype.search方法调用时,会返回该方法的返回值。

  1. String.prototype.search(regexp)
  2. // 等同于
  3. regexp[Symbol.search](this)
  4. class MySearch {
  5. constructor(value) {
  6. this.value = value;
  7. }
  8. [Symbol.search](string) {
  9. return string.indexOf(this.value);
  10. }
  11. }
  12. 'foobar'.search(new MySearch('foo')) // 0

Symbol.split

对象的Symbol.split属性,指向一个方法,当该对象被String.prototype.split方法调用时,会返回该方法的返回值。

  1. String.prototype.split(separator, limit)
  2. // 等同于
  3. separator[Symbol.split](this, limit)

下面是一个例子。

  1. class MySplitter {
  2. constructor(value) {
  3. this.value = value;
  4. }
  5. [Symbol.split](string) {
  6. let index = string.indexOf(this.value);
  7. if (index === -1) {
  8. return string;
  9. }
  10. return [
  11. string.substr(0, index),
  12. string.substr(index + this.value.length)
  13. ];
  14. }
  15. }
  16. 'foobar'.split(new MySplitter('foo'))
  17. // ['', 'bar']
  18. 'foobar'.split(new MySplitter('bar'))
  19. // ['foo', '']
  20. 'foobar'.split(new MySplitter('baz'))
  21. // 'foobar'

上面方法使用Symbol.split方法,重新定义了字符串对象的split方法的行为,

Symbol.iterator

对象的Symbol.iterator属性,指向该对象的默认遍历器方法。

  1. const myIterable = {};
  2. myIterable[Symbol.iterator] = function* () {
  3. yield 1;
  4. yield 2;
  5. yield 3;
  6. };
  7. [...myIterable] // [1, 2, 3]

对象进行for...of循环时,会调用Symbol.iterator方法,返回该对象的默认遍历器,详细介绍参见《Iterator 和 for…of 循环》一章。

  1. class Collection {
  2. *[Symbol.iterator]() {
  3. let i = 0;
  4. while(this[i] !== undefined) {
  5. yield this[i];
  6. ++i;
  7. }
  8. }
  9. }
  10. let myCollection = new Collection();
  11. myCollection[0] = 1;
  12. myCollection[1] = 2;
  13. for(let value of myCollection) {
  14. console.log(value);
  15. }
  16. // 1
  17. // 2

Symbol.toPrimitive

对象的Symbol.toPrimitive属性,指向一个方法。该对象被转为原始类型的值时,会调用这个方法,返回该对象对应的原始类型值。

Symbol.toPrimitive被调用时,会接受一个字符串参数,表示当前运算的模式,一共有三种模式。

  • Number:该场合需要转成数值
  • String:该场合需要转成字符串
  • Default:该场合可以转成数值,也可以转成字符串
  1. let obj = {
  2. [Symbol.toPrimitive](hint) {
  3. switch (hint) {
  4. case 'number':
  5. return 123;
  6. case 'string':
  7. return 'str';
  8. case 'default':
  9. return 'default';
  10. default:
  11. throw new Error();
  12. }
  13. }
  14. };
  15. 2 * obj // 246
  16. 3 + obj // '3default'
  17. obj == 'default' // true
  18. String(obj) // 'str'

Symbol.toStringTag

对象的Symbol.toStringTag属性,指向一个方法。在该对象上面调用Object.prototype.toString方法时,如果这个属性存在,它的返回值会出现在toString方法返回的字符串之中,表示对象的类型。也就是说,这个属性可以用来定制[object Object][object Array]object后面的那个字符串。

  1. // 例一
  2. ({[Symbol.toStringTag]: 'Foo'}.toString())
  3. // "[object Foo]"
  4. // 例二
  5. class Collection {
  6. get [Symbol.toStringTag]() {
  7. return 'xxx';
  8. }
  9. }
  10. let x = new Collection();
  11. Object.prototype.toString.call(x) // "[object xxx]"

ES6 新增内置对象的Symbol.toStringTag属性值如下。

  • JSON[Symbol.toStringTag]:’JSON’
  • Math[Symbol.toStringTag]:’Math’
  • Module 对象M[Symbol.toStringTag]:’Module’
  • ArrayBuffer.prototype[Symbol.toStringTag]:’ArrayBuffer’
  • DataView.prototype[Symbol.toStringTag]:’DataView’
  • Map.prototype[Symbol.toStringTag]:’Map’
  • Promise.prototype[Symbol.toStringTag]:’Promise’
  • Set.prototype[Symbol.toStringTag]:’Set’
  • %TypedArray%.prototype[Symbol.toStringTag]:’Uint8Array’等
  • WeakMap.prototype[Symbol.toStringTag]:’WeakMap’
  • WeakSet.prototype[Symbol.toStringTag]:’WeakSet’
  • %MapIteratorPrototype%[Symbol.toStringTag]:’Map Iterator’
  • %SetIteratorPrototype%[Symbol.toStringTag]:’Set Iterator’
  • %StringIteratorPrototype%[Symbol.toStringTag]:’String Iterator’
  • Symbol.prototype[Symbol.toStringTag]:’Symbol’
  • Generator.prototype[Symbol.toStringTag]:’Generator’
  • GeneratorFunction.prototype[Symbol.toStringTag]:’GeneratorFunction’

Symbol.unscopables

对象的Symbol.unscopables属性,指向一个对象。该对象指定了使用with关键字时,哪些属性会被with环境排除。

  1. Array.prototype[Symbol.unscopables]
  2. // {
  3. // copyWithin: true,
  4. // entries: true,
  5. // fill: true,
  6. // find: true,
  7. // findIndex: true,
  8. // includes: true,
  9. // keys: true
  10. // }
  11. Object.keys(Array.prototype[Symbol.unscopables])
  12. // ['copyWithin', 'entries', 'fill', 'find', 'findIndex', 'includes', 'keys']

上面代码说明,数组有 7 个属性,会被with命令排除。

  1. // 没有 unscopables 时
  2. class MyClass {
  3. foo() { return 1; }
  4. }
  5. var foo = function () { return 2; };
  6. with (MyClass.prototype) {
  7. foo(); // 1
  8. }
  9. // 有 unscopables 时
  10. class MyClass {
  11. foo() { return 1; }
  12. get [Symbol.unscopables]() {
  13. return { foo: true };
  14. }
  15. }
  16. var foo = function () { return 2; };
  17. with (MyClass.prototype) {
  18. foo(); // 2
  19. }

上面代码通过指定Symbol.unscopables属性,使得with语法块不会在当前作用域寻找foo属性,即foo将指向外层作用域的变量。