js css html

JavaScript 基本(二)symbol类型

2022-05-11  本文已影响0人  Viewwei

symbol是ES6新增的类型。符号是原始值,且符号实例是唯一的、不可变的。符号的用途是确保对象属性使用唯一标识符号
symbol需要使用Symbol()函数进行初始化,不能使用new进行初始化。typeof操作符返回的类型为symbol.使用相同参数声明的符号变量是不相等的

const a = Symbol("VIEW")
const b = Symbol("VIEW")
console.log(a===b) //false

如果运行时不同的部分需要共享和重用符号实例,那么就需要用一个字符串作为key,在全局符号注册表中创建并重用符号

const a = Symbol.for("a")
const b = Symbol.for("a")
console.log(a===b) //true

Symbol.for()对每个字符串都执行幂等操作,第一次使用某个字符串调用的时候,它会检查全局运行注册表中是否存在相应的符号,如果不存在,则直接生成,如果存在直接使用存在的符号。全局注册表中必须使用字符串创建

symbol内置符号

Symbol.asyncIterator

Symbol.asyncIterator由for-await-of语句使用

Symbol.hasInstance

Symbol作为一个属性表示一个方法,Symbol.hasInstance决定构造器对象是否认可一个对象是它的原型。由instanceof操作符号使用。

class Bar {}
class Baz extends Bar {
  static [Symbol.hasInstance]() {
    return false;
  }
}
// hasInstance 判断一个对象实例的原型链是否有原型
function hasInstance() {
  const b = new Baz();
  console.log(Baz[Symbol.hasInstance](b));
  console.log(b instanceof Baz);
}
Symbol.isConcatSpreadable

isConcatSpreadable这个符号操作符是一个布尔值,如果为true,则意味着对象应该由Array.prototype.concat()大屏数据元素,否则整个对象添加到数组末尾

function isConcatSpreadable() {
  const init = ["foo"];
  const array = ["value"];
  // console.log("array", init.concat(array));
  array[Symbol.isConcatSpreadable] = false;
  console.log("数据:", array[Symbol.isConcatSpreadable]);
  console.log("array", init.concat(array));
}

Symbol.iterator

iterator返回对象默认迭代器。由for-of使用

class Emitters {
  constructor(count) {
    this.count = count;
    this.idx = 0;
  }
  *[Symbol.iterator]() {
    while (this.idx < this.count) {
      yield this.idx++;
    }
  }
}
function count() {
  const emitter = new Emitters(10);
  for (const x of emitter) {
    console.log("x:", x);
  }
}
上一篇 下一篇

猜你喜欢

热点阅读