Appearance
Symbol
ES6 引入原始数据类型Symbol,独一无二的值。
作用:防止属性名冲突
JavaScript 六大数据类型:undefined、null、Boolean、String、Number、Object。现新增 Symbol
注意事项
- 原始类型不能使用 new,Symbol 也是原始类型
- 字符串做参数。参数只是为了区分 Symbol 值,参数一样并不代表 Symbol 值一样。
js
// 没有参数的情况
let s1 = Symbol()
let s2 = Symbol()
s1 === s2 // false
// 有参数的情况
let s1 = Symbol('foo')
let s2 = Symbol('foo')
s1 === s2 // false- 对象做参数,调用 toString,将其转为字符串
js
const obj = {
toString() {
return 'abc'
}
}
const sym = Symbol(obj)
sym // Symbol(abc)- Symbol 值显示转换,可以转为字符串、布尔值,不能转为数值
js
let sym = Symbol('My symbol')
// 字符串
String(sym) // 'Symbol(My symbol)'
sym.toString() // 'Symbol(My symbol)'
// 布尔值
let sym = Symbol()
Boolean(sym) // true
!sym // false
// 数值
Number(sym) // TypeError
sym + 2 // TypeErrorSymbol.prototype.description
ES2019 - 提供实例属性 description,返回 Symbol 描述
js
const sym = Symbol('foo')
String(sym) // "Symbol(foo)"
sym.toString() // "Symbol(foo)"
sym.description // "foo"作为属性名的 Symbol
Symbol 作为属性,保证不会出现同名属性
- Symbol 作为对象属性,不能用点运算符,因为点运算符后面总是字符串
js
const mySymbol = Symbol()
const a = {}
a.mySymbol = 'Hello!' // mySymbol 会转为 字符串
a[mySymbol] // undefined
a['mySymbol'] // "Hello!"- 对象内部,Symbol 值定义属性,必须放到方括号中,否则键名为字符串,而非 Symbol 值
js
let s = Symbol();
let obj = {
[s]: function (arg) { ... }
};
obj[s](123);消除魔术字符串
魔术字符串:代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。
场景
下面代码中“Triangle” 为魔术字符串
js
function getArea() {
switch (shape) {
case 'Triangle': // 魔术字符串
/* ... more code ... */
}
return area
}
getArea('Triangle') // 魔术字符串消除方法
- 通过变量消除
js
const shapeType = {
triangle: 'Triangle'
}
getArea(shapeType.triangle)- 实际变量值并不重要,通过
Symbol消除
js
const shapeType = {
triangle: Symbol()
}属性名遍历
for...in、for...of、Object.keys()、Object.getOwnPropertyNames()、JSON.stringify()中都不会遍历 Symbol 值
Object.getOwnPropertySymbols():获取指定对象的所有 Symbol 属性名。返回数组,成员为所有作属性名的 Symbol 值
js
const obj = {}
let a = Symbol('a')
let b = Symbol('b')
obj[a] = 'Hello'
obj[b] = 'World'
const objectSymbols = Object.getOwnPropertySymbols(obj)
objectSymbols
// [Symbol(a), Symbol(b)]用途:Symbol 值作为键名,不会被常规方法遍历得到这一特性,可以为对象定义一些非私有的、但又希望只用于内部的方法
js
let size = Symbol('size')
class Collection {
constructor() {
this[size] = 0
}
add(item) {
this[this[size]] = item
this[size]++
}
static sizeOf(instance) {
return instance[size]
}
}
let x = new Collection()
Collection.sizeOf(x) // 0
x.add('foo') // 0:'foo' Symbol(size): 1
Collection.sizeOf(x) // 1
Object.keys(x) // ['0']
Object.getOwnPropertyNames(x) // ['0']
Object.getOwnPropertySymbols(x) // [Symbol(size)]Reflect.ownKeys():返回所有类型的键名(包括 Symbol 键名)
Symbol.for()
Symbol.for():接受一个字符串作为参数,搜索以该参数作为名称的 Symbol 值。
- 有,返回 Symbol 值
- 无,新建一个以该字符串为名称的 Symbol 值,注册到全局
Symbol.for()与Symbol()区别
Symbol.for():
Symbol():直接新建
js
Symbol.for('bar') === Symbol.for('bar')
// true
Symbol('bar') === Symbol('bar')
// falseSymbol.for():在全局变量搜索,不存在才会新建。可以用在不同的 iframe 或 service worker 中取到同一个值。
js
iframe = document.createElement('iframe')
iframe.src = String(window.location)
document.body.appendChild(iframe)
iframe.contentWindow.Symbol.for('foo') === Symbol.for('foo') // trueSymbol.keyFor()
Symbol.keyFor():返回一个已登记的 Symbol 类型值的key
js
let s1 = Symbol.for('foo')
Symbol.keyFor(s1) // "foo"
let s2 = Symbol('foo')
Symbol.keyFor(s2) // undefined模块的 Singleton 模式
Singleton 模式:调用一个类,任何时候返回的都是同一个实例。
js
// mod.js//
const FOO_KEY = Symbol.for('foo')
function A() {
this.foo = 'hello'
}
if (!global._foo) {
global._foo = new A()
}
/*if (!global[FOO_KEY]) { global[FOO_KEY] = new A();}*/
module.exports = global._foo // module.exports = global[FOO_KEY];缺陷:global._foo可写入,任何文件都可以修改,在引入前修改值
解决:利用 Symbol,外部无法引用这个值(FOO_KEY),也无法改写
js
// mod.js
const FOO_KEY = Symbol.for('foo')
function A() {
this.foo = 'hello'
}
if (!global[FOO_KEY]) {
global[FOO_KEY] = new A()
}
module.exports = global[FOO_KEY]但也存在问题,多次执行,每次FOO_KEY不一样。虽然 Node 会将脚本的执行结果缓存,但用户可以手动清除缓存,所以也不是绝对可靠
内置 Symbol 值
作用:重新定义方法
Symbol.hasInstance
Symbol.hasInstance:指向一个内部方法。
调用时机:使用instanceof运算符,判断是否为该对象的实例时,会调用这个方法。
js
class MyClass {
[Symbol.hasInstance](foo) {
return foo instanceof Array
}
}
;[1, 2, 3] instanceof new MyClass() // trueSymbol.isConcatSpreadable
Symbol.isConcatSpreadable:一个布尔值。表示对象用于Array.prototype.concat()时,是否可以展开。
数组:默认(undefined)可展开
js
let arr1 = ['c', 'd']
;['a', 'b'].concat(arr1, 'e') // ['a', 'b', 'c', 'd', 'e']
arr1[Symbol.isConcatSpreadable] // undefined
let arr2 = ['c', 'd']
arr2[Symbol.isConcatSpreadable] = false
;['a', 'b'].concat(arr2, 'e') // ['a', 'b', ['c','d'], 'e']类数组:默认(undefined)不展开,值为true才可展开
js
let obj = { length: 2, 0: 'c', 1: 'd' }
;['a', 'b'].concat(obj, 'e') // ['a', 'b', obj, 'e']
obj[Symbol.isConcatSpreadable] = true
;['a', 'b'].concat(obj, 'e') // ['a', 'b', 'c', 'd', 'e']类中定义
js
class A1 extends Array {
constructor(args) {
super(args)
this[Symbol.isConcatSpreadable] = true
}
}
class A2 extends Array {
constructor(args) {
super(args)
}
get [Symbol.isConcatSpreadable]() {
return false
}
}
let a1 = new A1()
a1[0] = 3
a1[1] = 4
let a2 = new A2()
a2[0] = 5
a2[1] = 6
;[1, 2].concat(a1).concat(a2)
// [1, 2, 3, 4, [5, 6]]Symbol.species
Symbol.species属性:指向一个构造函数。创建衍生对象时,会使用该属性。
此代码,b,c 均为 a 的衍生对象。
js
class MyArray extends Array {}
const a = new MyArray(1, 2, 3)
const b = a.map((x) => x)
const c = a.filter((x) => x > 1)
b instanceof MyArray // true
c instanceof MyArray // true定义Symbol.species属性要采用get取值器。
js
// 默认写法
static get [Symbol.species]() {
return this;
}应用:子类使用继承的方法,希望返回基类的实例,而不是子类的实例。
js
class MyArray extends Array {
static get [Symbol.species]() {
return Array
}
}
const a = new MyArray()
const b = a.map((x) => x)
b instanceof MyArray // false
b instanceof Array // trueSymbol.match
Symbol.match属性:指向一个函数。执行str.match(myObject),如果该属性存在,会调用它,返回该方法的返回值。
js
String.prototype.match(regexp)
// 等同于
regexp[Symbol.match](this)
class MyMatcher {
[Symbol.match](string) {
return 'hello world'.indexOf(string)
}
}
'e'.match(new MyMatcher()) // 1Symbol.replace
Symbol.replace:指向一个方法,当该对象被String.prototype.replace方法调用时,会返回该方法的返回值。
js
String.prototype.replace(searchValue, replaceValue)
// 等同于
searchValue[Symbol.replace](this, replaceValue)
const x = {}
x[Symbol.replace] = (...s) => console.log(s)
'Hello'.replace(x, 'World') // ["Hello", "World"]Symbol.search
Symbol.search:指向一个方法,当该对象被String.prototype.search方法调用时,会返回该方法的返回值。
js
String.prototype.search(regexp)
// 等同于
regexp[Symbol.search](this)Symbol.split
Symbol.split:指向一个方法,当该对象被String.prototype.split方法调用时,会返回该方法的返回值。
js
String.prototype.split(separator, limit)
// 等同于
separator[Symbol.split](this, limit)Symbol.iterator
Symbol.iterator:指向该对象的默认遍历器方法。
进行for...of循环时,调用Symbol.iterator方法,返回该对象的默认遍历器
js
class Collection {
*[Symbol.iterator]() {
let i = 0
while (this[i] !== undefined) {
yield this[i]
++i
}
}
}
let myCollection = new Collection()
myCollection[0] = 1
myCollection[1] = 2
for (let value of myCollection) {
console.log(value)
}
// 1
// 2Symbol.toPrimitive
Symbol.toPrimitive:指向一个方法。该对象被转为原始类型的值时,会调用这个方法,返回该对象对应的原始类型值。
会接受一个字符串参数,一共有三种模式。
- Number:该场合需要转成数值
- String:该场合需要转成字符串
- Default:该场合可以转成数值,也可以转成字符串
js
let obj = {
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return 123
case 'string':
return 'str'
case 'default':
return 'default'
default:
throw new Error()
}
}
}
2 * obj // 246
3 + obj // '3default'
obj == 'default' // true
String(obj) // 'str'Symbol.toStringTag
Symbol.toStringTag:指向一个方法。在对象上面调用Object.prototype.toString方法时调用
属性存在,返回toString方法返回的字符串之中,表示对象的类型
js
Object.prototype.toString.call('foo') // "[object String]"
Object.prototype.toString.call([1, 2]) // "[object Array]"
Object.prototype.toString.call(3) // "[object Number]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
// 其他
Object.prototype.toString.call(new Map()) // "[object Map]"
Object.prototype.toString.call(function* () {}) // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()) // "[object Promise]"找不到,默认返回 Object
js
class ValidatorClass {}
Object.prototype.toString.call(new ValidatorClass()) // "[object Object]"定制 tag
js
// 例一
;({ [Symbol.toStringTag]: 'Foo' }.toString())
// "[object Foo]"
// 例二
class Collection {
get [Symbol.toStringTag]() {
return 'xxx'
}
}
let x = new Collection()
Object.prototype.toString.call(x) // "[object xxx]"Symbol.unscopables属性:指向一个对象。该对象指定了使用with关键字时,哪些属性会被with环境排除。
通过指定Symbol.unscopables属性,使得with语法块不会在当前作用域寻找foo属性,即foo将指向外层作用域的变量。
js
// 没有 unscopables 时
class MyClass {
foo() {
return 1
}
}
var foo = function () {
return 2
}
with (MyClass.prototype) {
foo() // 1
}
// 有 unscopables 时
class MyClass {
foo() {
return 1
}
get [Symbol.unscopables]() {
return { foo: true }
}
}
var foo = function () {
return 2
}
with (MyClass.prototype) {
foo() // 2
}Symbol.unscopables
Symbol.unscopables:指向一个对象。该对象指定了使用with关键字时,哪些属性会被with环境排除。
js
Array.prototype[Symbol.unscopables]
// {
// copyWithin: true,
// entries: true,
// fill: true,
// find: true,
// findIndex: true,
// includes: true,
// keys: true
// }使用
js
// 没有 unscopables 时
class MyClass {
foo() {
return 1
}
}
var foo = function () {
return 2
}
with (MyClass.prototype) {
foo() // 1
}
// 有 unscopables 时
class MyClass {
foo() {
return 1
}
get [Symbol.unscopables]() {
return { foo: true }
}
}
var foo = function () {
return 2
}
with (MyClass.prototype) {
foo() // 2
}