點燈坊

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

Why Number Literal has Instance Methods ?

Sam Xiao's Avatar 2021-12-19

We often use Number Literal in Practical, not Wrapper Object of Number. We can call instance method directly on Number Literal. But why?

Version

ECMAScript 2015

Sloppy Mode

Number.prototype.myMethod = function () {
  return {
    'typeof': typeof this,
    'instanceof': this instanceof Number
  }
}

let x = 1
x.myMethod () // ?

When calling myMethod in sloppy mode, Number Literal is converted to Wrapper Object first. That’s why we can call myMethod.

prototype000

Strict Mode

'use strict'

Number.prototype.myMethod = function () {
  return {
    'typeof': typeof this,
    'instanceof': this instanceof Number
  }
}

let x = 1
x.myMethod () // ?

When calling myMethod in strict mode, Number Literal is not converted to Wrapper Object. It calls Number.prototype.myMethod under the hood.

prototype001

Conclusion

  • Although we can call instance method directly on Number Literal in sloppy mode or strict mode, the underlying mechanism is different