In Javascript ES6, the use of the data type Symbol is described in detail.

Source: Internet
Author: User

In Javascript ES6, the use of the data type Symbol is described in detail.

Introduction

Symbol is a special and unchangeable data type. It can be used as an identifier of an object property to indicate unique values. The Symbol object is an implicit object wrapper of the symbol primitive data type.

It is the seventh data type in the JavaScript language. The first six data types are Undefined, Null, Boolean, String, Number, and Object.

Syntax

Symbol([description])

Parameters

Description: an optional string. Description of symbols that can be used for debugging but do not access the symbols themselves. If no parameter is added, all messages are printed on the console, which is difficult to distinguish.

Demo

var s1 = Symbol('symbol1');s1 //Symbol(symbol1);

Because the values returned by the Symbol function are unique, the values returned by the Symbol function are not equal.

// No parameter var s1 = Symbol (); var s2 = Symbol (); s1 = s2 // false // There is a parameter var s1 = Symbol ('symbol '); var s2 = Symbol ('symbol'); s1 = s2 // false

Symbol used as the attribute name

Because every Symbol value is not equal, it is a good choice as an attribute identifier.

Definition method:

Let symbolProp = Symbol (); var obj = {}; obj [symbolProp] = 'Hello symbol'; // or var obj = {[symbolProp]: 'Hello symbol ';} // or var obj ={}; Object. defineProperty (obj, symbolProp, {value: 'Hello symbol '});

Note:

When defining an attribute, you can only put the Symbol value in square brackets. Otherwise, the attribute's key name will be treated as a string rather than a Symbol value. Similarly, you cannot access the Symbol attribute through the dot operator. The dot operator is always followed by a string and does not read the Symbol value as the value referred to by the identifier.

Symbol type definition constant

The biggest benefit of using the Symbol value of a constant is that no other value can have the same value. It is a good way to design a switch statement. For example, remove the magic string (here, let readers think about it. If you have any questions, leave a message for me)

Symbol. for (), Symbol. keyFor ()

Symbol.for()

ForSymbol.forThere are two things to remember:

  • Symbol.for()The scope of the returned Symbol value is the entire code library (including different iframe or service worker). It is a global variable and will be registered at the first generation.
  • CallSymbol.for()If the given key exists in the global environment, a new value is created if it does not exist.Symbol()No,Symbol()Each return is a different value.
Symbol.for('foo') === Symbol.for('foo'); //trueSymbol('foo') === Symbol('foo'); //false

Symbol.keyFor()

Symbol.keyForMethod to return the key of a value of the registered Symbol type.

var s1 = Symbol.for('foo');Symbol.keyFor(s1) //"foo"var s2 = Symbol('foo');Symbol.keyFor(s2);//undefiend

In the above Code, variable s2 is an unregistered Symbol value, so undefined is returned.

Property name Traversal

Symbol is used as the attribute name. Although it is not a private attribute... In,... Of loop,Object.keys(),Object.getOwnPropertyNames()Will not be obtained. You can use two methods to traverse the Symbol attribute.

Object.getOwnPropertySymbolsMethod returns an array with the member attributes of all the Symbol values of the current object.

Reflect.ownKeys()You can return all types of key names, including general key names and Symbol key names.

The following is an example to illustrate all of the above.

Var obj = {}; var a = Symbol ('A'); var B = Symbol ('B'); obj [a] = 'hello '; obj [B] = 'World'; // for (var I in obj) {console. log (I); // No output} Object. getOwnPropertyNames (obj); // [] // you can obtain var objectSymbols = Object. getOwnPropertySymbols (obj); objectSymbols // [Symbol (a), Symbol (B)] Reflect. ownKeys (obj); // [Symbol (a), Symbol (B)]

The attribute with the Symbol value as the name is not obtained by the general method traversal. We can use this feature to define some non-private but only internal methods for objects.

var size = Symbol('size');class Collection { constructor(){ this[size] = 0; } add(item){ this[this[size]] = item; this[size]++; } static sizeOf(instance){ return instance[size]; }}var x = new Collection();Collection.sizeOf(x); //0x.add('foo');Collection.sizeOf(x); //1Object.keys(x)//['0']Object.getOwnPropertyNames(x) //['0']Object.getOwnPropertySymbols(x) //[Symbol(size)]

In the code above, the size attribute of object x is a Symbol value, soObject.keys(x) ,Object.getOwnPropertyNames(x)It cannot be obtained. This results in the effect of a non-private internal method. If you are not clear about ES6 definitions, you can skip this section or check your own documents. I will also share the following articles, in general, the new JavaScript standards are becoming more and more like Java, such as the newly added const, let block-level scope, and class definition class.

Built-in Symbol Value

In addition to its own defined Symbol values, JavaScript has some internal language behaviors represented by built-in Symbol that are not exposed to developers in ECMAScript 5 or earlier versions. These symbrs can be accessed by the following attributes:

1. Symbol. iterator

Returns the default iterator of an object. For... Of Usage

2. Symbol. math

The string matching method is also used to determine whether an object can be used as a regular expression.String.prototype.match().

3. Symbol. replace

A Method replaces a substring that matches a string. QuiltString.prototype.replace().

4. Symbol. search

Returns the method of returning indexes in a string that matches the regular expression. QuiltString.prototype.search().

5. Symbol. split

The method used to split a string at the index that matches the regular expression. QuiltString.prototype.split()Use.

6. Symbol. hasInstance

Determines whether the constructor object uses the object as an instance recognition method. Used by instanceof

7. Symbol. isConcatSpreadable

A boolean value that indicates whether the object should be flattened as an array element. QuiltArray.prototype.concat()Use.

8. Symbol. unscopables

Exclude its own and the value of the inherited property name from the Environment Binding of the associated object. Used by

9. Symbol. species

Create a constructor for the derived object.

10. Symbol. toPrimitive

The method to convert an object to the original value.

11. Symbol. toStringTag

String value used for the default description of the object. QuiltObject.prototype.toString()Use.

I didn't give a specific example here, for these 11 attributes. Readers can take the initiative to understand these attributes, which is very useful for understanding some methods.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.