你需要知道的Symbols

科技资讯 投稿 6400 0 评论

你需要知道的Symbols

著名symbol

    Symbol.iterator
  • Symbol.toStringTag
  • Symbol.toPrimitive
  • Symbol.asyncIterator
  • Symbol.hasInstance
  • Symbol.isConcatSpreadable
  • Symbol.species
  • Symbol.match
  • Symbol.matchall
  • Symbol.replace
  • Symbol.search
  • Symbol.split
  • Symbol.unscopables
  • Symbol.dispose

让我们看一些例子来了解其有用性。

Symbol.iterator

Symbol.iterator:该symbol被用来为对象定义默认的迭代器。它被用来在for-of循环中实现对对象的迭代,或用于扩展操作符。

const obj = { a: 1, b: 2, c: 3 };

obj[Symbol.iterator] = function*( {
  for (const key of Object.keys(this {
    yield [key, this[key]];
  }
};

for (const [key, value] of obj {
  console.log(`${key}: ${value}`;
}

Symbol.toStringTag

Symbol.toStringTag:该symbol被用来指定在调用Object.prototype.toString方法时返回的字符串值,以便为对象提供自定义的字符串表示形式。

class MyClass {
  static [Symbol.toStringTag] = 'MyClass';
}

const myInstance = new MyClass(;

console.log(myInstance.toString(; // outputs '[object MyClass]'

Symbol.toPrimitive

Symbol.toPrimitive:该symbol被用来指定对象在隐式调用valueOftoString方法时的行为。可以用它来为对象提供自定义的字符串和数字表示形式。

class Life {
  valueOf( {
    return 42;
  }

  [Symbol.toPrimitive](hint {
    switch (hint {
      case "number":
        return this.valueOf(;
      case "string":
        return "Forty Two";
      case "default":
        return true;
    }
  }
}

const myLife = new Life(;
console.log(+myLife; // 42
console.log(`${myLife}`; // "Forty Two"
console.log(myLife + 0; // 42

Symbol.asyncIterator

Symbol.asyncIterator:该symbol被用来为对象定义一个异步的迭代器。可以用它来为对象启用异步迭代。

class MyAsyncIterable {
  async *[Symbol.asyncIterator]( {
    for (let i = 0; i < 5; i++ {
      await new Promise(resolve => setTimeout(resolve, 1000;
      yield i;
    }
  }
}

(async ( => {
  for await (const value of new MyAsyncIterable( {
    console.log(value;
  }
}(;

// Output after one second:
// 0
// Output after two seconds:
// 1
// Output after three seconds:
// 2
// Output after four seconds:
// 3
// Output after five seconds:
// 4

Symbol.hasInstance

Symbol.hasInstance:该symbol被用来确认一个对象是否是构造函数的实例。它可以用来更改instanceof操作符的行为。

class MyArray {
  static [Symbol.hasInstance](instance {
    return Array.isArray(instance;
  }
}

const arr = [1, 2, 3];
console.log(arr instanceof MyArray; // true

Symbol.isConcatSpreadable

Symbol.isConcatSpreadable:该symbol被用来确定对象在与其他对象连接时是否应该被展开。它可以用来更改Array.prototype.concat方法的行为。

const arr1 = [1, 2, 3];
const spreadable = { [Symbol.isConcatSpreadable]: true, 0: 4, 1: 5, 2: 6, length: 3 };

console.log([].concat(arr1, spreadable; // [1, 2, 3, 4, 5, 6]

Symbol.species

Symbol.species:该symbol被用来指定创建派生对象时要使用的构造函数。它可以用来自定义创建新对象的内置方法的行为。

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

const myArray = new MyArray(1, 2, 3;
const mappedArray = myArray.map(x => x * 2;

console.log(mappedArray instanceof MyArray; // false
console.log(mappedArray instanceof Array; // true

P.S:这一功能在未来可能会被删除。

Symbol.match

Symbol.match:该symbol被用来在使用String.prototype.match

编程笔记 » 你需要知道的Symbols

赞同 (31) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽