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
.
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.
Conclusion
- Although we can call instance method directly on Number Literal in sloppy mode or strict mode, the underlying mechanism is different