Introduction to Symbol related knowledge in ES6 (code example)
This article brings you an introduction to Symbol-related knowledge in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
symbol is a type introduced in es6, and it also belongs to the category of primitive types (string, number, boolean, null, undefined, symbol)
basic
let name = Symbol('xiaohesong') typeof name // 'symbol' let obj = {} obj[name] = 'xhs' console.log(obj[name]) //xhs
symbol for
This thing is shareable. When it is created, it will check whether the symbol of this key is found globally. If it exists, the symbol will be returned directly. If it does not exist, it will be created and registered globally. .
let uid = Symbol.for("uid"); let object = { [uid]: "12345" }; console.log(object[uid]); // "12345" console.log(uid); // "Symbol(uid)" let uid2 = Symbol.for("uid"); console.log(uid === uid2); // true console.log(object[uid2]); // "12345" console.log(uid2); // "Symbol(uid)"The sharing mentioned here is global sharing, similar to global scope, and is shared in the entire environment.
symbol keyfor
let uid = Symbol.for("uid"); console.log(Symbol.keyFor(uid)); // "uid" let uid2 = Symbol.for("uid"); console.log(Symbol.keyFor(uid2)); // "uid" let uid3 = Symbol("uid"); console.log(Symbol.keyFor(uid3)); // undefined
The shared symbol uid3 does not exist in the global registry .So the corresponding key cannot be obtained. It can be seen that this is to obtain the corresponding key.
symbol cannot be forced to convert
let uid = Symbol('uid') uid + ''
An error will be reported here. According to the specification, it will convert uid into Strings are added. If you really want to add, you can add String(uid) first and then add, but at present, it seems to be meaningless.
Getting the symbol key in obj
let uid = Symbol('uid') let obj = { [uid]: 'uid' } console.log(Object.keys(obj)) // [] console.log(Object.getOwnPropertyNames(obj)) // [] console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(uid)]
es6 For this, the Object.getOwnPropertySymbols method was added.
Do you feel that Symbols are rarely used? In fact, there are still a lot of them used internally in es6.
Symbol.hasInstance
Every function has this method. Maybe you are not very familiar with this method, but it is actually what instanceof does. That's right, es6 rewrites this method for you.
function Xiao(){} const xiao = new Xiao xiao instanceof Xiao // true
Actually es6 does that for you
Xiao[Symbol.hasInstance](xiao)
This is an internal method and does not support rewriting. Of course, we can rewrite it on the prototype.
Object.definePrototype(Xiao, Symbol.hasInstance, { value: (v) : Boolean(v) }) const x = new Xiao x instanceof Xiao //true 0 instanceof Xiao //false 1 instanceof Xiao //true
It can be found that we rewrite it to return whether the corresponding value is a boolean type.
Symbol.isConcatSpreadable
This is different from other properties. It does not exist on some standard objects by default. Simply use
let objs = {0: 'first', 1: 'second', length: 2, [Symbol.isConcatSpreadable]: true} ['arrs'].concat(objs) //["arrs", "first", "second"]
Symbol.toPrimitive
. This is more useful. When performing type conversion, the object will try to convert to the original type, that is, through toPrimitive
.This method exists on prototypes of standard types.
When performing type conversion, toPrimitive
will be forced to call a parameter. In the specification, this parameter is called hint
. This parameter has three values ('number ', 'string', 'default') one of them.
As the name suggests, string
returns string
, number
returns number
, and default is not specified, the default.
So what is the default situation? In most cases, the default is numeric mode. (Except for date, its default situation is regarded as string mode)
In fact, there are not many default situations that are called during type conversion. Such as (==
,
) or when passing parameters to the constructor parameters of Date
.
number mode behavior in the case of numbers (priority from high to low)
First call valueOf, if it is a primitive type, Then return.
If the previous value is not the original value, then try to call toString. If it is the original value, then return
If it does not exist, then Report an error
string mode In the case of strings, the behavior is slightly different (priority from high to low)
First call toString , if it is the original value, then return
If the previous value is not the original value, then try to call valueOf, if it is the original value, then return
-
Throwing an error
Well, it feels a bit confusing, yes, let me explain the code.
let obj = { valueOf: function(){console.log('valueOf')}, toString: function(){console.log('toString')} } // console.log value is obj + 2 //valueOf obj == 2 // valueOf Number(obj) // valueOf String(obj) // toString
Through the above output, you can find that in most cases valueOf.
including the default case, the default is the number mode called, and most of them are the numbers called. mode, you can find that toString is the mode that calls string. So you can think that it is basically a numeric mode, unless it is a string mode.
Not very clear about this calling mode? It's okay, es6 exposes this internal method to the outside world, we can rewrite it and output the type of the hint. Come to
function Temperature(degrees) { this.degrees = degrees; } Temperature.prototype[Symbol.toPrimitive] = function(hint) { console.log('hint is', hint) }; let freezing = new Temperature(32); freezing + 2 // .. freezing / 2 // .. ...
the above types, you can try.
The above is the detailed content of Introduction to Symbol related knowledge in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!
