简体   繁体   中英

console.log and valueOf

After trying to solve an one little task I was a bit confused by the strange behavior of the console.log function. I expected that console.log will use the valueOf function as a converter of the object to the primitive value. But I was wrong...

It's better to explain with an example.

Number.prototype.sum = function sum(val) {
    var newVal = this + val;
    var f = sum.bind(newVal);
    f.valueOf = f.toString = function () {
        return newVal;
    };
    return f;
};

var numb = 50;
var res = numb.sum(10)(2)(2);
console.log(res);
alert(res);

I expected get the 64 in both of alert and console.log . But it's works only for alert as you can see at jsfiddle: http://jsfiddle.net/3yhrnrnL/

In the case of console.log I always getting something like "function b()" instead of 64 . Can someone explain me why it happens and how to fix it? Thanks!

The javascript alert expects a string and if it isn't provided a string it will attempt to convert that value into a string.

To get your console.log to work you can simply use the parseInt() function like so

Number.prototype.sum = function sum(val) {
    var newVal = this + val;
    var f = sum.bind(newVal);
    f.valueOf = f.toString = function () {
        return newVal;
    };
    return f;
};

var numb = 50;
var res = numb.sum(10)(2)(2);
console.log(parseInt(res));
alert(res);

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