JS-Symbol

Symbol应用场景:避免同名覆盖

声明定义Symbol的几种方法:

<script>
    //Symbol理解为:永远不会重复的字符串
    let hd = Symbol("123");
    console.log(hd);
    let stepback = Symbol.for("后撤步");
    console.log(stepback);

    let jameshd = Symbol("哈登");
    let js  = Symbol("脚本语言");
    console.log(jameshd);
    console.log(js.description);
    console.log(jameshd.toString());
</script>

Symbol.for()定义的变量,当两个Symbol.for()内的声明相同时,他们会引用同一片内存地址,区别于普通定义的Symbol();

<script>
    let james = Symbol.for("哈登");
    let harden = Symbol.for("哈登");

    console.log(james == harden);   //true
    console.log(james === harden);  //true

    let j = Symbol("哈登");
    let h = Symbol("哈登");
    console.log(j == h);            //false
    console.log(j === h);           //false
</script>

 

posted @ 2022-03-05 13:13  沉梦昂志_doc  阅读(129)  评论(0编辑  收藏  举报