ES6 javascript symbol data type __ES6

Source: Internet
Author: User

ES5 object property names are strings, which can easily cause property names to conflict. For example, if you use an object provided by another person but want to add a new method to the object (mixin mode), the name of the new method may conflict with the existing method. If there is a mechanism to ensure that the names of each attribute are unique, this will fundamentally prevent the conflict of property names. This is why ES6 introduced Symbol.

ES6 introduces a new primitive data type Symbol that represents a unique value. It is the seventh data type in the JavaScript language, the first six of which are: Undefined, Null, Boolean (Boolean), String (string), numeric (number), objects (object).

The symbol value is generated by the symbol function. This means that the object's property name can now have two types, one is the original string, and the other is the new Symbol type. All property names that are of type Symbol are unique and can be guaranteed to not conflict with other property names.

Let S = Symbol ();
typeof s
//"symbol"
In the code above, the variable s is a unique value. The result of the TypeOf operator indicates that the variable s is a Symbol data type, not another type such as a string.
Note that the symbol function cannot be used before the new command, or an error is noted. This is because the generated Symbol is a value of the original type, not an object. That is, the attribute cannot be added because the Symbol value is not an object. Basically, it's a data type similar to a string.
The symbol function can accept a string as a parameter, representing a description of the symbol instance, primarily to make it easier to distinguish between a console display and a string conversion.

var S1 = Symbol (' foo ');
var s2 = Symbol (' bar ');
S1//symbol (FOO)
s2/symbol (BAR)
s1.tostring ()//"Symbol (foo)"
s2.tostring ()//"Symbol (BAR)"
In the code above, S1 and S2 are two Symbol values. If you do not add parameters, their output in the console is symbol (), which is not conducive to distinction. With the parameters, it is equal to add a description of them, the output can be distinguished, in the end is which value.
Note that the parameter of the symbol function simply represents a description of the current symbol value, so the return value of the symbol function for the same parameter is not equal.

  case with no parameters
var s1 = Symbol ();
var s2 = Symbol ();
S1 = = S2//False
//  with parameters in the case of
var S1 = Symbol ("foo");
var s2 = Symbol ("foo");
S1 = = S2//False
In the code above, S1 and S2 are the return values of the symbol functions, and the parameters are the same, but they are not equal.
The Symbol value cannot be calculated with a value of another type, and an error is made.

var sym = symbol (' my Symbol ');
Your symbol is "+ sym
//typeerror:can ' t convert symbol to string
' your symbol ' ${sym} '
//TYPEERROR:C A ' t convert symbol to string
However, the Symbol value can be explicitly converted to a string.

var sym = symbol (' my Symbol ');
String (SYM)//' symbol (my symbol) '
sym.tostring ()//' symbol (my symbol) '
In addition, the Symbol value can be converted to a Boolean value, but cannot be converted to a value.

var sym = Symbol ();
Boolean (SYM)//True
!sym//False
if (sym) {
//...
}
Number (SYM)//TypeError
Sym + 2//TypeError


To use symbol as the property name

Because each symbol value is unequal, this means that the symbol value can be used as an identifier for the object's property name to guarantee that no property of the same name will appear. This is useful for an object that is composed of multiple modules, preventing a key from being accidentally overwritten or overwritten.

var mysymbol = Symbol ();
The  first type is the
var a = {};
A[mysymbol] = ' hello! ';
The  second way of writing
var a = {
[Mysymbol]: ' hello! '
};
The  third type of the
var a = {};
Object.defineproperty (A, Mysymbol, {value: ' hello! '});
The  above writing all get the same result
A[mysymbol]///"hello!"


Symbol.for (), Symbol.keyfor ()

Sometimes we want to reuse the same Symbol value, and the Symbol.for method can do that. It takes a string as a parameter and then searches for a symbol value with the parameter as the name. If it does, it returns the symbol value, or it creates a new and returns a symbol value with the string name.

var S1 = symbol.for (' foo ');
var s2 = symbol.for (' foo ');
S1 = = S2//True
In the above code, both S1 and S2 are Symbol values, but they are all generated by the Symbol.for method of the same parameter, so they are actually the same value.

Both the symbol.for () and symbol () will generate a new symbol. The difference is that the former will be registered in the global environment for searching, which will not. Symbol.for () does not return a new Symbol type value each time it is invoked, but first checks whether the given key already exists and creates a new value if it does not exist. For example, if you call Symbol.for ("cat") 30 times, the same symbol value is returned each time, but calling Symbol ("cat") 30 times returns 30 different symbol values.

Symbol.for ("bar") = = = Symbol.for ("bar")
//True
symbol ("bar") = = = Symbol ("bar")
//False
In the code above, because the symbol () method does not have a registration mechanism, each call returns a different value.
The Symbol.keyfor method returns the key for a registered Symbol type value.

var S1 = symbol.for ("foo");
Symbol.keyfor (S1)//"foo"
var s2 = Symbol ("foo");
Symbol.keyfor (s2)//undefined
In the code above, the variable S2 belongs to the unregistered Symbol value, so it returns undefined.
It should be noted that Symbol.for is the name registered for the Symbol value, which is the global environment, and can be taken to the same value in different IFRAME or service worker.

iframe = document.createelement (' iframe ');
IFRAME.SRC = String (window.location);
Document.body.appendChild (IFRAME);
Iframe.contentWindow.Symbol.for (' foo ') = = symbol.for (' foo ')
/True
In the code above, the Symbol value generated by the iframe window can be obtained on the main page.











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.