知名符号
知名符号是一些具有特殊含义的共享符号,通过Symbol的静态属性得到
例子
1.Symbol.hasInstance:该符号用于定义构造函数的静态成员,它将影响instance的判定
function A() {
}
const a = new A();
console.log(a instanceof A);
function A() {
}
//改变instance的判定
Object.defineProperty(A, Symbol.hasInstance, {
value: function (obj) {
return false;
}
})
const a = new A();
console.log(a instanceof A);
console.log(A[Symbol.hasInstance](a));
2.Symbol.isConcatSpreadable:该知名符号会影响数组的 concat 方法
const arr1 = [1];
const arr2 = [2, 3, 4, 5];
const result = arr1.concat(1, arr2)
console.log(result)
const arr1 = [1];
const arr2 = [2, 3, 4, 5];
arr2[Symbol.isConcatSpreadable] = false;
const result = arr1.concat(1, arr2)
console.log(result)
3.Symbol.toPrimitive:该知名符号会影响类型转换的结果
class Temperature {
constructor(degree) {
this.degree = degree;
}
}
const t = new Temperature(90);
console.log(t + "!");
console.log(t / 2);
console.log(String(t));
class Temperature {
constructor(degree) {
this.degree = degree;
}
[Symbol.toPrimitive](type) {
if (type === "default") {
return this.degree + "度";
}
else if (type === "number") {
return this.degree;
}
else if (type === "string") {
return this.degree + "℃";
}
}
}
const t = new Temperature(90);
console.log(t + "!");
console.log(t / 2);
console.log(String(t));
4.Symbol.toStringTag:该知名符号会影响 Object.prototype.toString 的返回值
class Person {
}
const p = new Person();
const arr = [1, 2, 3]
console.log(Object.prototype.toString.apply(p));
console.log(Object.prototype.toString.apply(arr));
class Person {
[Symbol.toStringTag] = "随意改";
}
const p = new Person();
const arr = [1, 2, 3];
console.log(Object.prototype.toString.apply(p));
console.log(Object.prototype.toString.apply(arr));
5.其他很多知名符号,感兴趣的同学可以自行查阅官方文档