JavaScript Symbol type: (non-string object keys)

前端 未结 3 1414
没有蜡笔的小新
没有蜡笔的小新 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.
    
    0 讨论(0)
  • 2021-01-05 07:50

    I thought object keys were strings only

    You're right, but that was true for EcmaScript 5 only. ES 6 / harmony is a draft for something new!

    I'm trying to make sense of the spec

    It's a draft only, rapidly changing. How symbols are used and whether or how they can be created by arbitrary scripts does not seem to have settled yet (scan through the versions for changes).

    If you scroll down to the very end of that document (even below Annex F), you for example will see a Section 8.4.4: Symbol Exotic Objects that has been moved out there. It states

    Exotic Symbol objects provide alternative definitions for all of the essential internal methods.

    You can see them used at section 8.1.7.4 Well-Known Symbols and Intrinsics for example. For proposed uses (and still existing problems / open questions) of Symbol constructors have a look at these strawman pages or this wiki site.

    0 讨论(0)
  • 2021-01-05 07:57

    Symbol is a new addition to the language proposed as part of ECMAScript 6:

    Current work on ECMAScript™

    Work on future ECMAScript™ editions continues as part of the previously announced ECMAScript™ "Harmony" project. More details of the current work on ECMAScript "Harmony" are described on this Wiki. A sixth edition of the standard is currently under development with a target date of December 2013 for completion.

    0 讨论(0)
提交回复
热议问题