javascript中的symbol

symbol的使用

功能

类似于一种标志唯一性的ID

理解唯一性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


</head>
<body>
<script>

    let s1=Symbol()
    let s2=Symbol("hello world")
    let s3=Symbol("hello world")
    console.log(s1==s2)//false
    console.log(s2==s3)//false
</script>
</body>
</html>

用symbol作为对象的属性名(相当于私有化)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


</head>
<body>
<script>

    const NAME = Symbol()
    const AGE = Symbol()
    let obj = {
        [NAME]: "PeiEn", //NAME:"PeiEn"是错误形式
        hobby: "basketball"
    }
    obj[AGE] = 18
    console.log(obj)

    //取值

    console.log(Object.keys(obj)) //枚举不到symbol  [hobby]

    for (let o in obj) {
        console.log(o)  //枚举不到symbol
    }
    console.log(Object.getOwnPropertyNames(obj))//枚举不到symbol

    console.log(JSON.stringify(obj));//枚举不到symbol

//-------------------------------------------------------------------
    //只能取到私有的
    console.log(Object.getOwnPropertySymbols(obj))

    //可以取到全部
    console.log(Reflect.ownKeys(obj))


</script>
</body>
</html>

用symbol代替一些常量

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


</head>
<body>
<script>

   //如果定义一些枚举性的常量
   //尽量去使用一些symbol,可以更安全,也能更美观
   const s1=Symbol()
   const s2=Symbol()
   const s3=Symbol()
   
</script>
</body>
</html>
posted @ 2024-07-28 23:42  Bre-eZe  阅读(6)  评论(0编辑  收藏  举报