eterey
eterey

Reputation: 420

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!

Upvotes: 2

Views: 1282

Answers (1)

Canvas
Canvas

Reputation: 5897

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);

Upvotes: 2

Related Questions