Pure function given strictly equal arguments yielding non-strictly equal results

后端 未结 6 626
执念已碎
执念已碎 2021-01-04 12:59

Below is a pure function f for which f(a) !== f(b) despite a === b (notice the strict equalities) for some values of a<

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 13:22

    In ECMAScript 3, another example where === behaves surprisingly is with joined functions. Consider a case like this:

    function createConstantFunction(result) {
        return function () {
            return result;
        };
    }
    
    var oneReturner = createConstantFunction(1);  // a function that always returns 1
    var twoReturner = createConstantFunction(2);  // a function that always returns 2
    

    An implementation is allowed to "join" the two functions (see §13.2 of the spec), and if it does so, then oneReturner === twoReturner will be true (see §13.1.2), even though the two functions do different things. Similarly with these:

    // a perfect forwarder: returns a sort of "duplicate" of its argument
    function duplicateFunction(f) {
        return function (f) {
            return f.apply(this, arguments);
        };
    }
    
    var myAlert = duplicateFunction(alert);
    console.myLog = duplicateFunction(console.log);
    

    Here an implementation can say that myAlert === console.myLog, even though myAlert is actually equivalent to alert and console.myLog is actually equivalent to console.log.

    (However, this aspect of ECMAScript 3 was not preserved in ECMAScript 5: functions are no longer allowed to be joined.)

提交回复
热议问题