gpt4 book ai didi

javascript - 在 JS 中,为什么我能够使用诸如 toFixed() 之类的函数,它驻留在原始类型的 Number 包装器对象的原型(prototype)中?

转载 作者:行者123 更新时间:2023-12-03 16:31:59 25 4
gpt4 key购买 nike

在 JavaScript 中,原始类型(数字、字符串等)不是对象。因此,它们没有 [[prototype]],因此无法使用某些对象的 [[prototype]] 中可用的方法。
而 Number、String 是包装对象,可用于创建带有 new 的变量。关键字,我们可以在这些变量上使用 Number 对象原型(prototype)中可用的方法(使用 new 关键字创建)。
但是在给定的代码中,我创建了一个原始类型变量,并且能够使用像 toFixed() 这样的方法。它驻留在数字对象中。
这让我很困惑。请详细说明这一点。

let a = 6.678; //primitive type

a= a.toFixed(1); // toFixed() resides in prototype of Number Object

console.log(a); // 6.7

最佳答案

这与称为“自动装箱”的概念有关,Javascript 看到您正在尝试访问原始类型的属性,因此在运行时很短的时间内,它将原始值转换为其相应的 Wrapper 对象和继续进行属性调用,然后在大多数情况下将值转换回原始类型。

let a = 6.678; //primitive type

a= a.toFixed(1); // JS converts a to "Number Object" and then the function is called

console.log(a); // 6.7
这是一个很好的答案 Does javascript autobox?

关于javascript - 在 JS 中,为什么我能够使用诸如 toFixed() 之类的函数,它驻留在原始类型的 Number 包装器对象的原型(prototype)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65445497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com