简体   繁体   中英

console.log outputs 'function <valueOf result> ' instead of '<valueOf result>'

I am reading the javascript manual and I have wtote following code:

//sum
function sum(arg1) {
    var sum = arg1;

    function f(arg2) {
        sum += arg2;
        return f;
    };

    f.valueOf = function () {
        return sum;
    };

    f.toString = function () {
        return sum;
    };

    return f;
}

and I execute it like this:

console.log(sum(1)(2)(3)(4));

According the manual console.log should output the result of valueOf function

but it output

function 10

please explain this behaviour.

According the manual console.log should output the result of valueOf function

I don't know what "manual" you're talking about, but in general, console.log doesn't call valueOf on what you output. The implementations of console.log vary from JavaScript engine to JavaScript engine, but in general they try to give you more useful information than calling valueOf would.

If you want to trigger valueOf , you'll need to do that intentionally, for instance:

console.log(sum(1)(2)(3)(4).valueOf());
// ------------------------^^^^^^^^^^

or (since your function is designed to produce a number):

console.log(+sum(1)(2)(3)(4));
// ---------^

Example:

 function sum(arg1) { var sum = arg1; function f(arg2) { sum += arg2; return f; }; f.valueOf = function () { return sum; }; f.toString = function () { return sum; }; return f; } console.log(sum(1)(2)(3)(4).valueOf()); // ------------------------^^^^^^^^^^ console.log(+sum(1)(2)(3)(4)); // ---------^ 
 Look in the actual browser console; the Stack Snippets console doesn't quite do what the real browser console does. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM