当前位置:网站首页>JS的装箱和拆箱
JS的装箱和拆箱
2022-07-03 02:19:00 【weixin_49035434】
装箱转换
每一种基本类型Number、String、Boolean、Symbol在对象中都有对应的类,所谓装箱转换,正是把基本类型转换为对应的对象,它是类型转换中一种相当重要的种类。
前文提到,全局的 Symbol 函数无法使用 new 来调用,但我们仍可以利用装箱机制来得到一个 Symbol 对象,我们可以利用一个函数的call方法来强迫产生装箱。
我们定义一个函数,函数里面只有return this,然后我们调用函数的call方法到一个Symbol类型的值上,这样就会产生一个symbolObject。
我们可以用console.log看一下这个东西的type of,它的值是object,我们使用symbolObject instanceof 可以看到,它是Symbol这个类的实例,我们找它的constructor也是等于Symbol的,所以我们无论从哪个角度看,它都是Symbol装箱过的对象:
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
装箱机制会频繁产生临时对象,在一些对性能要求较高的场景下,我们应该尽量避免对基本类型做装箱转换。
使用内置的 Object 函数,我们可以在JavaScript代码中显式调用装箱能力。
var symbolObject = Object(Symbol("a"));
console.log(typeof symbolObject); //object
console.log(symbolObject instanceof Symbol); //true
console.log(symbolObject.constructor == Symbol); //true
每一类装箱对象皆有私有的 Class 属性,这些属性可以用 Object.prototype.toString 获取:
var symbolObject = Object(Symbol("a"));
console.log(Object.prototype.toString.call(symbolObject)); //[object Symbol]
在 JavaScript 中,没有任何方法可以更改私有的 Class 属性,因此Object.prototype.toString 是可以准确识别对象对应的基本类型的方法,它比 instanceof 更加准确。
但需要注意的是,call本身会产生装箱操作,所以需要配合 typeof 来区分基本类型还是对象类型。
拆箱转换
在JavaScript标准中,规定了 ToPrimitive 函数,它是对象类型到基本类型的转换(即,拆箱转换)。
对象到 String 和 Number 的转换都遵循“先拆箱再转换”的规则。通过拆箱转换,把对象变成基本类型,再从基本类型转换为对应的 String 或者 Number。
拆箱转换会尝试调用 valueOf 和 toString 来获得拆箱后的基本类型。如果 valueOf 和 toString 都不存在,或者没有返回基本类型,则会产生类型错误 TypeError。
var o = {
valueOf : () => {console.log("valueOf"); return {}},
toString : () => {console.log("toString"); return {}}
}
o * 2
// valueOf
// toString
// TypeError
我们定义了一个对象o,o有valueOf和toString两个方法,这两个方法都返回一个对象,然后我们进行o*2这个运算的时候,你会看见先执行了valueOf,接下来是toString,最后抛出了一个TypeError,这就说明了这个拆箱转换失败了。
到 String 的拆箱转换会优先调用 toString。我们把刚才的运算从o*2换成 String(o),那么你会看到调用顺序就变了。
var o = {
valueOf : () => {console.log("valueOf"); return {}},
toString : () => {console.log("toString"); return {}}
}
String(o)
// toString
// valueOf
// TypeError
在 ES6 之后,还允许对象通过显式指定 @@toPrimitive Symbol 来覆盖原有的行为。
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边栏推荐
- GBase 8c系统表pg_cast
- iptables 4层转发
- [shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)
- GBase 8c系统表-pg_collation
- Job object of collaboration in kotlin
- Su Shimin: 25 principles of work and life
- [Yu Yue education] China Ocean University job search OMG reference
- Trial setup and use of idea GoLand development tool
- es6 filter() 数组过滤方法总结
- udp接收队列以及多次初始化的测试
猜你喜欢

可視化yolov5格式數據集(labelme json文件)

The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}

How do it students find short-term internships? Which is better, short-term internship or long-term internship?

4. 类和对象

《上市风云》荐书——唯勇气最可贵

SPI机制

How to deal with cache hot key in redis

Use go language to realize try{}catch{}finally

Producer consumer model based on thread pool (including blocking queue)

微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
随机推荐
Current situation and future of Web3 in various countries
[shutter] pull the navigation bar sideways (drawer component | pageview component)
使用Go语言实现try{}catch{}finally
【ROS进阶篇】第六讲 ROS中的录制与回放(rosbag)
[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
oauth2.0鉴权,登录访问 “/oauth/token”,请求头Authorization(basicToken)如何取值???
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
How do browsers render pages?
8 free, HD, copyright free video material download websites are recommended
Swift development learning
[codeforces] cf1338a - Powered addition [binary]
Detailed introduction to the usage of Nacos configuration center
Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt
单词单词单词
Summary of ES6 filter() array filtering methods
Su Shimin: 25 principles of work and life
我的创作纪念日
Coroutinecontext in kotlin
Awk from getting started to being buried (2) understand the built-in variables and the use of variables in awk
Leetcode (540) -- a single element in an ordered array