you need to know exactly how it is executed when Number is called.
according to the js specification, if the parameter is object , the object will be first converted to primitive type data, so how to convert it to primitive type data?
such as
let a = {}
then the valueOf method of a is called first. If the result is not of the original type, then the toString method is called:
a.valueOf () returns the object itself, not the original type, so you need to continue to call the toString method.
a.toString () returns "[object Object]" , which is a string and original type, so next call Number ("[object Object]") to return NaN ;
so if you want to return a number, we can change the result by changing the return value in the conversion step, for example, we can change the return value of valueOf :
let a = {}
a.valueOf = function () {return 2}
Number(a) // 2
or modify the return value of toString :
let b = {}
b.toString = function () {return 3}
Number(b) // 3
reference link
- specification
it is said that ES5.1,
Number will perform toNumber operations on the parameters. The returned value of toNumber is as follows
let flag = false;
Number (flag)
/ / 0
let b = new Boolean (false);
b / / Boolean {false}
Number (b)
/ / 0
can be converted, will be automatically packaged and unpacked (packing type) default false-> 0, true-> 1
I wonder if that's what you're asking? If not, you can cut down what is said in the book, where you don't understand