點燈坊

失くすものさえない今が強くなるチャンスよ

Using Primitive Wrapper Object to Wrap Number

Sam Xiao's Avatar 2021-12-19

In addition to using Primitive for Number, we can use Primitive Wrapper Object to wrap Number.

Version

ECMAScript 2015

typeof

let x = 1
let y = new Number (1) // ?

typeof x // ?
typeof y // ?
  • x is Number Literal
  • y is a Wrapper Object for Number
  • typeof :
    • Number Literal : number
    • Wrapper Object : object

object000

instanceOf

let x = 1
let y = new Number (1) // ?


x instanceof Number // ?
y instanceof Number // ?

instanceof :

  • Number Literal : false
  • Wrapper Object : true

object001

valueOf

let x = 1
let y = new Number (1) // ?

x === y.valueOf () // ?

We can use valueOf to unwrap Wrapper Object.

object002

Number

let x = 1
let y = new Number (1) // ?

x === Number (y) // ?

We can also use Number to unwrap Wrapper Object.

object003

Dynamic Property

let x = 1
let y = new Number (1) // ?

y.id = 2

y // ?
y.id // ?

Since Wrapper Object is an Object, we can add a new property to Primitive Wrapper Object.

object004

Conclusion

  • Primitive Wrapper Object is immutable. We can’t modify the inner value of Wrapper Object

Reference

MDN, Number