当前位置:网站首页>Packing and unpacking of JS
Packing and unpacking of JS
2022-07-03 02:21:00 【weixin_ forty-nine million thirty-five thousand four hundred an】
boxing conversion
Every basic type Number、String、Boolean、Symbol There are corresponding classes in the object , So called packing conversion , It's the conversion of basic types to corresponding objects , It is a very important kind of type conversion .
As mentioned above , Overall Symbol Function cannot be used new To call , But we can still use the boxing mechanism to get a Symbol object , We can use a function's call Method to force the generation of boxing .
Let's define a function , There are only return this, Then we call the... Of the function call Method to one Symbol On a value of type , This will create a symbolObject.
We can use console.log Take a look at the... Of this thing type of, Its value is object, We use symbolObject instanceof You can see , It is Symbol An instance of this class , We're looking for it constructor Is equal to Symbol Of , So no matter what angle we look at it , It's all Symbol Boxed objects :
var symbolObject = (function(){ return this; }).call(Symbol("a"));
console.log(typeof symbolObject); //object
console.log(symbolObject instanceof Symbol); //true
console.log(symbolObject.constructor == Symbol); //true
The boxing mechanism often produces temporary objects , In some high performance scenarios , We should try to avoid boxing conversions to basic types .
Use the built-in Object function , We can do it in JavaScript Explicitly call boxing capability in code .
var symbolObject = Object(Symbol("a"));
console.log(typeof symbolObject); //object
console.log(symbolObject instanceof Symbol); //true
console.log(symbolObject.constructor == Symbol); //true
Each type of boxed object has a private Class attribute , These properties can be used Object.prototype.toString obtain :
var symbolObject = Object(Symbol("a"));
console.log(Object.prototype.toString.call(symbolObject)); //[object Symbol]
stay JavaScript in , There is no way to change private Class attribute , therefore Object.prototype.toString It is a method that can accurately identify the basic types of objects , It is better than instanceof More accurate .
But it should be noted that ,call Itself will produce packing operation , So we need to cooperate with typeof To distinguish the basic type from the object type .
Unpacking conversion
stay JavaScript In the standard , Specifies the ToPrimitive function , It is the conversion from object type to basic type ( namely , Unpacking conversion ).
Object to String and Number All conversions follow “ Unpacking before conversion ” The rules of . Conversion by unpacking , Turn objects into basic types , Then convert from the basic type to the corresponding String perhaps Number.
Unpacking transformation will try to call valueOf and toString To get the basic type after unpacking . If valueOf and toString It doesn't exist , Or it doesn't return the basic type , Type error will be generated TypeError.
var o = {
valueOf : () => {console.log("valueOf"); return {}},
toString : () => {console.log("toString"); return {}}
}
o * 2
// valueOf
// toString
// TypeError
We define an object o,o Yes valueOf and toString Two methods , Both methods return an object , And then we do o*2 When this operation , You will see that the first execution valueOf, Next is toString, Finally threw a TypeError, This indicates that the unpacking conversion failed .
To String The unpacking conversion of will call... First toString. Let's start the operation from o*2 Switch to String(o), Then you will see that the calling order changes .
var o = {
valueOf : () => {console.log("valueOf"); return {}},
toString : () => {console.log("toString"); return {}}
}
String(o)
// toString
// valueOf
// TypeError
stay ES6 after , It also allows objects to be specified explicitly @@toPrimitive Symbol To cover the original behavior .
var o = {
valueOf : () => {console.log("valueOf"); return {}},
toString : () => {console.log("toString"); return {}}
}
o[Symbol.toPrimitive] = () => {console.log("toPrimitive"); return "hello"}
console.log(o + "")
// toPrimitive
// hello边栏推荐
- Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
- Unrecognized SSL message, plaintext connection?
- 《上市风云》荐书——唯勇气最可贵
- Leetcode (540) -- a single element in an ordered array
- Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
- Use go language to realize try{}catch{}finally
- 返回一个树形结构数据
- Solution for processing overtime orders (Overtime unpaid)
- How to deal with cache hot key in redis
- Depth (penetration) selector:: v-deep/deep/ and > > >
猜你喜欢

SPI机制

Create + register sub apps_ Define routes, global routes and sub routes

stm32F407-------IIC通讯协议

Visual yolov5 format data set (labelme JSON file)

微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題

Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux

Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)

Machine learning notes (constantly updating...)

Thread safe singleton mode

Awk from introduction to earth (0) overview of awk
随机推荐
【教程】chrome关闭跨域策略cors、samesite,跨域带上cookie
GBase 8c 创建用户/角色 示例二
各国Web3现状与未来
Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque
Kotlin middle process understanding and Practice (II)
Unrecognized SSL message, plaintext connection?
Method of removing webpage scroll bar and inner and outer margins
我的创作纪念日
require. context
My creation anniversary
What are the key points often asked in the redis interview
GBase 8c 触发器(一)
Leetcode (540) -- a single element in an ordered array
String replace space
Current situation and future of Web3 in various countries
5.文件操作
[Yu Yue education] reference materials of chemical experiment safety knowledge of University of science and technology of China
Servlet中数据传到JSP页面使用el表达式${}无法显示问题
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem