Does valueOf always override toString in javascript?

后端 未结 3 1233
太阳男子
太阳男子 2021-02-20 03:44

Is there any expression where by an object\'s toString method is implicitly called overriding its valueOf method?

In the examples below, valueOf is alw

3条回答
  •  后悔当初
    2021-02-20 04:30

    The + operator on Date objects uses toString not valueOf. Also if valueOf returns a non-primitive value then the toString method is called next. (JavaScript - The definitive guide, section 3.14) Using your example:

    var result = "4" + {
        toString: function () {
            return "4";
        },
        valueOf: function () {
            return this; // returning an object, not a primitive
        }
    };
    

    Result is now 44.

提交回复
热议问题