In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces what Symbol is in JavaScript, it has certain reference value, interested friends can refer to it, I hope you can learn a lot after reading this article, let the editor take you to understand it.
What is Symbol? Why is there such a thing?
Symbol (symbol) is a new data type for ES6. Symbol is the original value (the underlying data type), and the Symbol instance is unique and immutable. It is generated because it is used as a unique tag and, in turn, as an object property in the form of a non-string, to ensure that the object property uses a unique identifier and does not have the risk of property conflicts. [related recommendation: javascript Learning tutorial]
Usage 1. Basic usage
The symbol needs to be initialized using the Symbol () function. Because the symbol itself is a primitive type, the typeof operator returns symbol for the symbol.
Let sym = Symbol (); console.log (typeof sym); / / symbol
The Symbol () function can take a string parameter to describe, which can then be used to debug the code. It is worth noting, however, that multiple Symbol () functions do not have the same values even if they accept the same parameters.
Let genericSymbol = Symbol (); let otherGenericSymbol = Symbol (); let fooSymbol = Symbol ("foo"); let otherFooSymbol = Symbol ("foo"); console.log (genericSymbol = = otherGenericSymbol); / / falseconsole.log (fooSymbol = = otherFooSymbol); / / false2. Use the global symbol registry
If you need to use the same Symbol instance in multiple places in your code, you can pass in a string, and then use the Symbol.for () method to create a reusable Symbol, similar to the singleton pattern. When you use Symbol.for () for the first time, it will globally find out whether the same instance has been created using Symbol.for () according to the passed parameters. If so, reuse it. If not, create a new one.
Let fooGlobalSymbol = Symbol.for ("foo"); / / create new symbols let otherFooGlobalSymbol = Symbol.for ("foo"); / / reuse existing symbols console.log (fooGlobalSymbol = otherFooGlobalSymbol); / / true
The difference between the instance created by Symbol.for () and that created by Symbol (): the instance created by Symbol () is always unique and will not be equal to other instances because the parameters you pass in are the same, but the instances created by Symbol.for () will be equal if the parameters are the same, because they will share the same Symbol instance.
Let fooSymbol = Symbol ("foo"); let otherFooSymbol = Symbol ("foo"); console.log (fooSymbol = = otherFooSymbol); / / falselet fooGlobalSymbol = Symbol.for ("foo"); / / create new symbols let otherFooGlobalSymbol = Symbol.for ("foo"); / / reuse existing symbols console.log (fooGlobalSymbol = otherFooGlobalSymbol); / / true3. Use symbols as attributes
The properties in objects are generally in the form of strings, but you can also use Symbol instances as properties. The advantage is that the new properties you add will not overwrite any previous properties.
Let S1 = Symbol ("foo"), S2 = Symbol ("bar"), S3 = Symbol ("baz"), S4 = Symbol ("qux"); let o = {[S1]: "foo val",}; / / it is also possible: o [S1] = 'foo val';console.log (o); / / {Symbol (foo): foo val} Object.defineProperty (o, S2, {value: "bar val"}); console.log (o) / / {Symbol (foo): foo val, Symbol (bar): bar val} Object.defineProperties (o, {[S3]: {value: "baz val"}, [S4]: {value: "qux val"},}); console.log (o); / / {Symbol (foo): foo val, Symbol (bar): bar val,// Symbol (baz): baz val, Symbol (qux): qux val}
Note: when creating an Symbol instance as an object property, if symbol does not declare a variable to receive at the beginning, you must traverse all the symbolic attributes of the object to find the corresponding property key:
Let o = {[Symbol ("foo")]: "foo val", [Symbol ("bar")]: "bar val",}; console.log (o); / / {Symbol (foo): "foo val", Symbol (bar): "bar val"} let barSymbol = Object.getOwnPropertySymbols (o) .find (symbol = > symbol.toString (). Match (/ bar/)); console.log (barSymbol); / / Symbol (bar) 4. Common built-in symbols
ES6 also introduces a number of commonly used built-in symbols (well-known symbol) to expose language internal behaviors that developers can directly access, rewrite, or simulate. If you modify these default properties, you can change the final result of some operations. For example, if the for-of loop uses the Symbol.iterator property on the related object, you can change the behavior of for-of when iterating over the object by redefining the value of Symbol.iterator on the custom object.
5. Symbol.asyncIterator
In fact, it is a Generator that returns Promise, which is usually used with for await of
6. Symbol.hasInstance
According to the ECMAScript specification, this symbol represents as an attribute "a method that returns the object's default AsyncIterator. Used by the for-await-of statement." In other words, this symbol represents a function that implements the asynchronous iterator API.
This property is defined on the prototype of Function. It is well known that the instanceof operator can be used to determine whether an object instance belongs to a constructor. The principle is that the instanceof operator uses the Symbol.hasInstance function to determine the relationship.
Function Foo () {} let f = new Foo (); console.log (f instanceof Foo); / / trueclass Bar {} let b = new Bar (); console.log (b instanceof Bar); / / true
If you redefine the Symbol.hasInstance property of a function, you can make the instanceof method return something unexpected
Class Bar {} class Baz extends Bar {static [Symbol.hasInstance] () {return false;}} let b = new Baz (); console.log (bar [Symbol.hasInstance] (b)); / / trueconsole.log (b instanceof Bar); / / trueconsole.log (Baz.hasInstance] (b)); / / falseconsole.log (b instanceof Baz); / / falseSymbol.isConcatSpreadabl
This property is defined on the prototype of Array
According to the ECMAScript specification, this symbol represents "a Boolean value as an attribute, which, if true, means that the object should flatten its array elements with Array.prototype.concat ()." The Array.prototype.concat () method in ES6 chooses how to concatenate an array of class (pseudo-array) objects into an array instance based on the type of object received. So you can change this behavior by changing the value of Symbol.isConcatSpreadable.
The corresponding effect of Symbol.isConcatSpreadable
False: add an entire object to the array true: add an entire pairing to the array
Let initial = ["foo"]; let array = ["bar"]; console.log (Array [Symbol.isConcatable]); / / undefinedconsole.log (initial.concat (array)); / / ['foo',' bar'] array [Symbol.isConcatSpreadable] = false;console.log (initial.concat (array)); / / ['foo', Array (1)] let arrayLikeObject = {length: 1,0: "baz"}; console.log (ArrayLikeObject [Symbol.isConcatSpreadable]) / / undefinedconsole.log (initial.concat (arrayLikeObject)); / ['foo', {...}] arrayLikeObject [Symbol.isConcatSpreadable] = true;console.log (initial.concat (arrayLikeObject)); / / [' foo', 'baz'] let otherObject = new Set (). Add ("qux"); console.log (other object [Symbol.isConcatSpreadable]); / / undefinedconsole.log (initial.concat (otherObject)); / / [' foo', Set (1)] otherObject[ Symbol.isConcatSpreadable] = true Console.log (initial.concat (otherObject)) / / ['foo'] 8. Symbol.iterator
According to the ECMAScript specification, this symbol represents as an attribute "a method that returns the object's default iterator. Used by the for-of statement"
This property returns a Generator function, and for of calls the next () method in turn, which is why for of can be used on some objects.
Class Emitter {constructor (max) {this.max = max; this.idx = 0;} * [Symbol.iterator] () {while (this.idx < this.max) {yield this.idx++;} function count () {let emitter = new Emitter (5); for (const x of emitter) {console.log (x);}} count () Symbol.match
According to the ECMAScript specification, this symbol represents as an attribute "a regular expression method that uses regular expressions to match strings. Used by the String.prototype.match () method."
The String.prototype.match () method uses a function with Symbol.match as the key to evaluate the regular expression. So changing the Symbol.match property of a regular expression allows String.prototype.match () to get the value you want.
Console.log [Symbol.match] () {[native code]} console.log ("foobar" .match (/ bar/)); / / ["bar", index: 3, input: "foobar", groups: undefined] class FooMatcher {static [Symbol.match] (target) {return target.includes ("foo");} console.log ("foobar" .match (FooMatcher)) / / trueconsole.log ("barbaz" .match (FooMatcher)); / falseclass StringMatcher {constructor (str) {this.str = str;} [Symbol.match] (target) {return target.includes (this.str);}} console.log ("foobar" .match (new StringMatcher ("foo"); / / trueconsole.log ("barbaz" .match (new StringMatcher ("qux"); / / false11. Symbol.search
This symbol represents as an attribute "a regular expression method that returns the index in the string that matches the regular expression. Used by the String.prototype.search () method"
12. Symbol.species
This symbol represents "a function value as a constructor to create a derived object" as an attribute.
13. Symbol.split
This symbol represents as an attribute "a regular expression method that splits the string at the index that matches the regular expression. Used by the String.prototype.split () method."
14. Symbol.toPrimitive
This symbol represents, as an attribute, "a method that converts the object to the corresponding original value. Used by ToPrimitive abstract operations"
15. Symbol.toStringTag
This symbol represents as an attribute "a string that is used to create the default string description of the object. Used by the built-in method Object.prototype.toString ()"
16. Symbol.unscopables
As an attribute, this symbol represents "an object, all of which and inherited properties are excluded from the with environment binding of the associated object."
Thank you for reading this article carefully. I hope the article "what is Symbol in JavaScript" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.