我在读《Javascript高级程序设计》一书时,当读到Number Type下对于Number()
函数转化规则一部分时,发现他有如下一个介绍:
When applied to objects, the valueOf() method is called and the
returned value is converted based on the previously described rules.
If that conversion results in NaN, the toString() method is called and
the rules for converting strings are applied.
按照它的描述,我的理解是,对于一个Object,先执行Object的valueOf()函数,如果最后转化结果是NaN,就再采用Object的toString()函数进行转化。
但是我做了如下实验:
var obj = { a: "hello", valueOf: function() { return this.a; }, toString: function() { return 1; } }Number(obj) // 结果:NaN
所以是不是书里描述错误了,应该是如果没有valueOf()函数的时候才执行toString(),否则只是执行valueOf()
繁花如伊
相关分类