当前位置:网站首页>ES6 learning road 5 symbol
ES6 learning road 5 symbol
2022-06-30 09:09:00 【Ancient dust left Taidao】
List of articles
brief introduction
The emergence of new methods or things , It always needs to be accompanied by the ability to solve some problems .Symbol
The emergence of data types is to solve the problem that variable attribute names are the same .
Code up
const s = Symbol()
console.log(s) // Symbol()
console.log(typeof s) // symbol
This creates a Symbol
Variable of type s
, My understanding here is , hold s
As a Symbol
Variable of type .
Symbol
Function that can accept arguments , Accepting parameters is just a distinction
const s = Symbol('foo')
const t = Symbol('bar')
console.log(s) // Symbol(foo)
console.log(t) // Symbol(bar)
it is to be noted that Symbol
The return value of the function is a new memory space ,s
,t
,p
,q
Are all reference types
const s = Symbol()
const t = Symbol()
console.log(s === t) // false
const p = Symbol('foo')
const q = Symbol('foo')
console.log(p === q) // false
symbol
Value cannot be operated on with other types of values
const s = Symbol()
console.log(s + '') // Cannot convert a Symbol value to a string
but symbol
What can be displayed is converted to a string
const s = Symbol()
console.log(String(s)) // Symbol()
symbol
It can also be converted to a Boolean value , To tell you the truth, I don't think it's useful here
const s = Symbol()
console.log(Boolean(s)) // true
obtain Symbol Description of
obtain symbol Can be described in description
attribute
const s = Symbol('foo')
console.log(s.description) // foo
There are three ways to make symbol
As property name
const s = Symbol('foo')
const obj = {
}
The first way to write it
// obj[s] = 1
The second way
/* Object.defineProperty(obj, s, { value: 1 }) */
The third way
/* const obj = { [s]: 1 } */
Learn here , I am right. symbol
The understanding of , Take the example above ,s It's equivalent to a symbol
Variable of type , Also a key
value , however s
It cannot be understood as a string , Because the above values are not used .
Operator .
Eliminate magic strings
My understanding is , Use... In functions if
Statement or switch
Statement to determine equality , such as if(data === 'xiaoyuan')
, If this xiaoyuan
The string has been judged many times , So it's the magic string , Such a trick , Not conducive to program maintenance , It's really bad for , For example, in the future xiaoyuan
To change to another string , There are a lot of changes to be made . The best thing is to make it a variable , Describe it in code as follows .
const username = {
xiaoyuan: 'xiaoyuan'
}
function getUserInfoByUserName(name) {
if (name === username.xiaoyuan) {
return 'success'
} else {
throw new Error('fail')
}
}
getUserInfoByUserName(username.xiaoyuan)
If the product manager tells you , Each name of the user is different , that key
by xiaoyuan
Of value
Value is actually not so important , At this time, you just need to ensure that each user value If the value is different . So you can use symbol
const username = {
xiaoyuan: Symbol()
}
function getUserInfoByUserName(name) {
if (name === username.xiaoyuan) {
return 'success'
} else {
throw new Error('fail')
}
}
getUserInfoByUserName(username.xiaoyuan)
Object.getOwnPropertySymbols() Method to get symbol Attribute array
symbol
The value of type cannot be traversed by ordinary traversal , such as Object.keys
Method ,for in
,for of
wait , obtain symbol
Properties need to be used Object.getOwnPropertySymbols()
Method
Example :
const xiaoyuan = Symbol('xiaoyuan')
const dayuan = Symbol('dayuan')
const username = {
[xiaoyuan]: 1,
[dayuan]: 2
}
for (item in username) {
console.log(item) // Nothing
}
console.log(Object.getOwnPropertySymbols(username)) // [Symbol(xiaoyuan), Symbol(dayuan)]
Feeling time
See here , My heart is in great pain , Because I think this knowledge point is too boring , And I haven't met in the project at present . So learning is very painful , I looked at the progress bar , And half symbol
knowledge , Oh my god , Hold on to it , After learning, I will brush Tiktok to reward myself .
Symbol.for(), Symbol.keyfor() Method
Symbol.for()
Code to show the difference
const demo1 = Symbol('foo')
const demo2 = Symbol('foo')
console.log(demo1 === demo2) // false
const demo3 = Symbol.for('bar')
const demo4 = Symbol.for('bar')
console.log(demo3 === demo4) // true
My understanding is ,Symbol.for
Method can also create a Symbol
Variable of type , But with Symbol()
The difference is , When it is created, it will be registered globally ,
in other words , Use Symbol.for('bar')
When the method is used , It will look in the code first , See if you have declared this in your previous code Symbol.for('bar')
, If there is , Just use the previous one , To put it bluntly demo3
,demo4
The pointer to the heap is the same . A more common understanding is to see if there is any in the stack area , If you have one, take the pointer and use it .
Symbol.keyfor()
Symbol.keyfor()
Method returns with Symbol.for
Of the created attribute key
word , It's the string you passed in
<script>
const demo1 = Symbol('foo')
const demo3 = Symbol.for('bar')
console.log(Symbol.keyFor(demo1))// undefined
console.log(Symbol.keyFor(demo3)) // bar
Built in Symbol value
Symbol
Yes 11 A native built-in value , To put it mildly, those big guys helped you do 11 individual js
Built in Symbol
Variable
1.Symbol.hasInstance
Determine whether an instance belongs to this class , It can be used instanceof
keyword , When using instanceof
When the operator , Will call... In the class Symbol.hasInstance
The way to point , here instanceof
The operator has 2 Usage
class Demo {
static [Symbol.hasInstance](foo) {
console.log('hello') // hello
}
}
const demo = new Demo()
console.log(demo instanceof Demo) // false
class Demo {
[Symbol.hasInstance](foo) {
console.log('hello') // hello
}
}
const demo = new Demo()
console.log([1, 2, 3] instanceof demo) // false
I don't understand this place , Didn't learn well , I'll add later .
2.Symbol.isConcatSpreadable
Please refer to my other article for this place js Of concat Method
To be added ...
Blog
Welcome to my blog www.smartxy.cc
边栏推荐
- Detectron2 source code reading 4-- registrar construction model
- Codeworks 5 questions per day (1700 for each) - the third day
- Based on svelte3 X desktop UI component library svelte UI
- 基于Svelte3.x桌面端UI组件库Svelte UI
- Rew acoustic test (I): microphone calibration
- About MySQL Boolean and tinyint (1)
- JPA naming rules
- Dart basic notes
- 关于Lombok的@Data注解
- Opencv learning notes -day4 image pixel reading and writing operations (array traversal and pointer traversal implementation, uchar vec3b data type and mat class functions mat:: at(), mat:: ptr())
猜你喜欢
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.
Do you want the dialog box that pops up from the click?
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Flink Exception -- No ExecutorFactory found to execute the application
VIM from dislike to dependence (21) -- cross file search
Bottomsheetbehavior principle of realizing the home page effect of Gaode map
Anchorgenerator for mmdet line by line interpretation
The elegant combination of walle and Jianbao
Maxiouassigner of mmdet line by line interpretation
El input limit can only input numbers
随机推荐
C#訪問SQL Server數據庫兩種方式的比較(SqlDataReader vs SqlDataAdapter)
Dart basic notes
Wechat development tool (applet)
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.
Get to know handler again
Detailed explanation of pytoch's scatter function
Opencv learning notes -day1 (image reading display imread, imshow, namedwindow)
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
Esp32 (IX): OTA function of function development
Introduction to MySQL foundation power node [Lao Du] class assignment
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"
CUDA realizes L2 European distance
Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
CUDA implements matrix replication
证券开户的优惠怎样才能得到?在线开户安全?
127.0.0.1、0.0.0.0和localhost
Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)
QT downloading files through URL
[wechat applet] realize applet pull-down refresh and pull-up loading