JavaScript Symbol type __javascript

Source: Internet
Author: User
JavaScript Symbol type

Depending on the specification, the object property key can only be string or symbol type, not number, Boolean, only string and symbol two types.
We typically compare attribute string, and now look at the advantages that the symbols type brings to us. symbols

The "Symbol" value represents a unique identity with the given name. This type of value can be created like this: Symbol (name):

ID is a symbol with the name ' ID ' let
id = symbol (' id '); 

Symbols make sure that the unique, even if we use the same name, will produce different values. For example, there are two symbol uses the same name, two are not equal:

Let id1 = Symbol ("id");
Let Id2 = Symbol ("id");

Alert (Id1 = = Id2); False

If you are familiar with Ruby or other languages and have the same type of symbol, don't be misled, JavaScript symbol is different. Hide Properties

Symbol allows you to create hidden properties of objects so that other code does not occasionally access or overwrite them.
For example, if we want to store the "identifier" of the object user, we can create the ID symbol:
Let user = {name: "John"};
Let id = Symbol ("id");

User[id] = "id Value";
Alert (User[id]); We can access the data using the symbol as the key

Now let's imagine assuming that another script wants to add its own "id" attribute to the user object for its own purposes. It could be another JavaScript library, so it's completely unclear to each other.
No problem, you can create your own symbol ("id").

The code is as follows:

// ...
Let id = Symbol ("id");

User[id] = "Their ID value";

This is not a conflict, because symbol is always different, even if it has the same name. Note that if we use the string "id" instead of symbol to achieve the same purpose, there is a conflict:

Let user = {name: "John"};

Our script uses "id" property
user.id = "id Value";

... if later another script the uses "id" for its purposes ...

User.ID = "Their ID value"
//boom! overwritten! It did not mean to harm the colleague, but did it!
Direct Volume use symbol

If we use symbol in a direct-measure object, we need to use square brackets:

Let id = Symbol ("id");

Let user = {
  name: ' John ',
  [ID]: 123//Not just ' id:123 '
};

Because we need the value of the symbol variable with the name "id", not the string "ID." Symbol is for...in ignored

The symbol property does not participate in for. In loop, for example:

Let id = Symbol ("id");
Let user = {
  name: "John",
  age:30,
  [ID]: 123
};

For (let key in user) alert (key); Name, age (no symbols)

//The direct access by the symbol Works
alert ("Direct:" + user[id]);

This is part of the general hidden concept, and if other scripts or libraries do not expect to access the symbol property.
Instead, object.assign copies both character and symbol attributes.

Let id = Symbol ("id");
Let user = {
  [id]: 123
};

Let clone = Object.assign ({}, user);

Alert (Clone[id]); 123

There is no contradiction between the two, and the norm is designed so that when we clone objects or merge objects, we usually want the symbol attribute to be copied as well.

Other types of property keys are cast to a string:

The keys in an object can only use strings or symbol, and other types are forced to be turned into strings.

Let obj = {
  0: ' Test '//Same as ' 0 ': ' Test '
}

//Both alerts access the same property (the number 0 is con verted to string "0")
alert (obj["0"]);//Test
alert (obj[0]);//Test (same property)
Global Symbol

Normally, all symbol is different, but sometimes we think symbol of the same noun is the same. For example, we apply a different section of symbol that wants to access the noun "id", of course it needs to be the same.
The implementation can be registered through global symbol, and we can create and then access them and ensure that the same symbol is repeatedly accessed through the same noun.

Created or read in registration, using the syntax: symbol.for (name), for example:

Read from the ' Global Registry let
name = symbol.for (' name ');//If the Symbol did not exist, it is created

//R EAD it again let
nameagain = symbol.for ("name");

The same symbol
alert (name = = = Nameagain);//True

Symbol in registration is called global symbol, and if we have an application-scoped symbol, the code can be accessed and you can use global symbol.

Other programming languages, like Ruby, each noun has a single symbol, and in JavaScript we know that it is the global symbol. symbol.keyfor

For global symbol, not only symbol.for (name), return Symbol by name, but also the opposite call: Symbol.keyfor (name), the reverse function: Returns a name based on global symbol.
Example:

Let sym = symbol.for ("name");
Let sym2 = symbol.for ("id");

Get name from Symbol
alert (symbol.keyfor (SYM));//Name
alert (symbol.keyfor (SYM2);//ID

Symbol.keyfor an internal implementation that uses global symbol registration to find the symbol name based on symbol.
Therefore, the non-global symbol does not function, and if it is not global symbol, it cannot be found and returned to undefined.

Example:

Alert (symbol.keyfor ("name")) (symbol.for); Name, global symbol

alert (symbol.keyfor symbol ("name2"));//undefined, non-global symbol

Non-global symbol with name only for debugging purposes. system Symbol

There are many system symbol inside JavaScript, and we can use them to adjust various aspects of the object.
Here is a list of some commonly used symbol:Symbol.hasInstance symbol.isconcatspreadable symbol.iterator symbol.toprimitive ...

For example: Symbol.toprimitive describes objects when they are used for basic types of objects, and if you continue to delve into JavaScript, others will become familiar. Summary symbol is the basic type that implements a unique identity create symbol by calling symbol (name) we create a field that is accessible only to people who know the symbol, and symbol is useful for symbols that do not appear in for. In results the symbol created with symbol (name) is always different, even if the name is the same. If you want the symbol of the same name to be equal, use global registration Symbol.for (name) to return global symbol for the given name, and multiple calls return the same symbol JavaScript with system symbol, accessed through symbol.*. We can use them to modify some of the built-in behaviors.

Technically, symbol is not 100% hidden, there are built-in methods Object.getownpropertysymbols (obj) to get all of the symbol.
There is also a method Reflect.ownkeys (obj) returns all the keys for the object, including symbol.

So it's not really hidden. But most library built-in methods and syntax structures follow common conventions they are hidden, and if someone shows up to invoke the above method, they may fully understand what he is doing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.