ES6——Symbol内置值

参考书籍链接:https://es6.ruanyifeng.com/#docs/generator-async

1.Symbol.hasInstance

对象的 Symbol.hasInstance 属性,指向一个内部方法。当其他对象使用 instanceof 运算符,判断是否为该对象的实例时,会调
用这个方法。比如, 
[1,2,3] instanceof new TT()
在语言内部,实际调用的是 Foo[Symbol.hasInstance](foo) 。
class TT{
    [Symbol.hasInstance](foo){
        return foo instanceof Array;
    }
}
[1,2,3] instanceof new TT(); //true

class DD{
}
[1,2,3] instanceof new DD(); //报错,必须在类中定义Symbol.hasInstance方法,才能使用【*** instanceof 该类的类名】。

 2.

对象的 Symbol.isConcatSpreadable 属性等于一个布尔值,表示该对象使用 Array.prototype.concat() 时,是否可以展开。
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']
 
let obj = {length: 4, 1: 'c', 2: 'd'};
['a', 'b'].concat(obj, 'e') // ['a', 'b', obj, 'e']
obj[Symbol.isConcatSpreadable] = true;
['a', 'b'].concat(obj, 'e') // ['a', 'b', empty, 'c', 'd', empty, 'e']
 
上面代码说明,数组的默认行为是可以展开。 Symbol.isConcatSpreadable 属性等于 true 或 undefined ,都有这个效果。类似数组的对象(参考:js在类似数组的对象中使用push
也可以展开,但它的 Symbol.isConcatSpreadable 属性默认为 false ,必须手动打开。
let obj = {length: 2, 0: 'c', 1: 'd'};//'c', 'd'的key为索引值。作为类似数组的对象
['a', 'b'].concat(obj, 'e') // ['a', 'b', obj, 'e']
obj[Symbol.isConcatSpreadable] = true;['a', 'b'].concat(obj, 'e') // ['a', 'b', 'c', 'd', 'e']
对于一个类来说, Symbol.isConcatSpreadable 属性必须写成实例的属性。
class A1 extends Array {
 constructor(args) {
 super(args);
this[Symbol.isConcatSpreadable] = true; } }
class A2 extends Array {
 constructor(args) {
 super(args);
this[Symbol.isConcatSpreadable] = 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]]
原文地址:https://www.cnblogs.com/sunupo/p/15492835.html