javascript中的symbol

Bre-eZe發表於2024-07-28

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>

相關文章