JavaScript Symbol type: (non-string object keys)

前端 未结 3 1413
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 07:35

What is the "Symbol" javascript type as mentioned in this ECMAScript 6 draft specification?

To quote the spec:

The Symbol type is the se

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 07:49

    We use symbols to make properties or methods of an object private. So we hide the details and show only the essentials. It is called abstraction.

    How to implement this:Let's create a simple class with "radius" property

    class Circle {
        constructor(radius) {
            this.radius = radius; 
        }
        }
    

    A symbol is essentially a unique identifier. Every time we call this function we get a unique identifier. It is not a constructor function,though.

    Symbol()===Symbol() //will be false
    

    Implementation:

    const _radius=Symbol()
    class Circle {
        constructor(radius) {
        this[_radius] = radius; //since property name starts with _, we use bracket notation
            }
             }
    

    now test this. Create an instance of Circle:

    const c=new Circle;
    console.log(Object.getOwnPropertyNames(c))// you will see a number on the console.
    

提交回复
热议问题