What can Symbol do? Why master it?

Speaking of Symbol, let's start with the basic data types string, number, boolean, null, undefined in js. Symbol is the sixth basic data type in js.

To describe Symbol in one sentence is unique!

Use of Symbol

Basic use

const s1 = Symbol('song');
const s2 = Symbol('song');
// Identity in Symbol is typically placed in number s, string s
console.log(s1 === s2); // Variables declared by Symbol are not equal

Symbol as key

    const s1 = Symbol('song');
    let obj = {
        [s1]:'song', // es6 grammar [] can use the value of symbol s as an attribute
        age:18
    }
    for(let key in obj){ // The for loop cannot traverse the symbol s property
        console.log(obj[key])
    }
    // The Reflect.ownKeys method takes all key attributes
    Reflect.ownKeys(obj).forEach(key=>{
        console.log(obj[key]);
    })

Symbol.for

We said above that symbols are unique, but sometimes I want to reuse declared symbols, use for grammar, declare if symbols do not exist, and return the created symbols if they exist!

const s1 = Symbol.for('song');
const s2 = Symbol.for('song');

console.log(s1 === s2);
console.log(Symbol.keyFor(s2)); // You can get the key of the symbox through keyFor

Symbol metaprogramming

Metaprogramming: You can modify the operation of native js, in other words, you can change the behavior of native JS

ES6 provides 11 built-in Symbol values

1.Symbol.hasInstance

Rewrite instanceof default behavior

const instance = {
    [Symbol.hasInstance](value){
        return 'a' in value
    }
}
// When the instance of method is called, the hasInstance method on the instance is called by default.
console.log({a:1} instanceof instance)

2.Symbol.isConcatSpreadable

Expansion behavior of overridden arrays

const arr = [1,2,3];
arr[Symbol.isConcatSpreadable] = false;
console.log(arr.concat([1,2,3]));

3.Symbol.match / split / search / replace

Matching, splitting, searching methods for rewritten strings

const obj = {
    [Symbol.match](value){
        return value.length === 3
    }
}
console.log('abc'.match(obj));

4.Symbol.species

When creating a derived object, specify the constructor

class MyArray extends Array{
    constructor(...args){
        super(...args);
    }
    static get [Symbol.species](){
        return Array; // Array is used as a constructor to create derived objects
    }
}
const arr = new MyArray(1,2,3);
const newArr = arr.map(item=>item*2);
console.log(newArr instanceof MyArray); // The default derived object is also an example of MyArray

5.Symbol.toPrimitive

Rewrite Data Type Conversion

const obj = {
    [Symbol.toPrimitive](type){ // type number string default
        return 123;
    }
}
console.log(obj*123);

6.Symbol.toStringTag

Rewriting toString method

const obj = {
  [Symbol.toStringTag]: "xxx"
};
console.log(Object.prototype.toString.call(obj)); // [object xxx]

7.Symbol.unscopables

Which attributes are overridden by with

console.log(Array.prototype[Symbol.unscopables]); // Which methods can't be used with
with(Array.prototype){ // Direct calls to methods on array prototypes
    forEach.call([1,2,3],element => {
        console.log(element)
    });
}

class MyClass {
  eat() {}
  get [Symbol.unscopables]() {
    return { eat: true }; // Not available under with
  }
}
with (MyClass.prototype) {
  console.log(eat);
}

The last Symbol.iterator is still missing. Leave a small tail and step on it to see what it does!! This interview is often asked.~

So far, we've gone through the use of Symbol. Of course, metaprogramming is rarely used in development. But we have the ability to rewrite the js language itself!

` Welcome to continue to pay attention to the public number: "Front-end optimization"
Continuous updating of technology, please continue to pay attention to... __________.`

Keywords: Javascript Attribute

Added by dgnorton on Mon, 26 Aug 2019 13:20:21 +0300