What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

前端 未结 5 1265
囚心锁ツ
囚心锁ツ 2020-11-21 06:25

The \'Wat\' talk for CodeMash 2012 basically points out a few bizarre quirks with Ruby and JavaScript.

I have made a JSFiddle of the results at http://jsfid

5条回答
  •  隐瞒了意图╮
    2020-11-21 06:47

    I second @Ventero’s solution. If you want to, you can go into more detail as to how + converts its operands.

    First step (§9.1): convert both operands to primitives (primitive values are undefined, null, booleans, numbers, strings; all other values are objects, including arrays and functions). If an operand is already primitive, you are done. If not, it is an object obj and the following steps are performed:

    1. Call obj.valueOf(). If it returns a primitive, you are done. Direct instances of Object and arrays return themselves, so you are not done yet.
    2. Call obj.toString(). If it returns a primitive, you are done. {} and [] both return a string, so you are done.
    3. Otherwise, throw a TypeError.

    For dates, step 1 and 2 are swapped. You can observe the conversion behavior as follows:

    var obj = {
        valueOf: function () {
            console.log("valueOf");
            return {}; // not a primitive
        },
        toString: function () {
            console.log("toString");
            return {}; // not a primitive
        }
    }
    

    Interaction (Number() first converts to primitive then to number):

    > Number(obj)
    valueOf
    toString
    TypeError: Cannot convert object to primitive value
    

    Second step (§11.6.1): If one of the operands is a string, the other operand is also converted to string and the result is produced by concatenating two strings. Otherwise, both operands are converted to numbers and the result is produced by adding them.

    More detailed explanation of the conversion process: “What is {} + {} in JavaScript?”

提交回复
热议问题