Holybreath Holybreath - 2 months ago 7
Javascript Question

Can valueOf() / toString() be overriden and inherited?

So I'm doing personal research, and trying to learn more about JavaScript inheritance etc. I've stumbled upon a question. Examine the code.

var x = function() {}, y = 10;
x.valueOf = function() {
return y + 10;
}
x.prototype.valueOf = function() {
return y + 5;
}
var z = new x();
console.log(z, x); // x {valueOf: function} 20
x.prototype.valueOf = x.valueOf;
var k = new x();
console.log(k, x); //x {valueOf: function} 20 the same!


I am trying to make braceless method calls. I understand valueOf can be used for this, but same is with
toString
. But, with toString I shouldn't be able having result of
console.log(z, x)
as 20 for
x
.

Answer
x.prototype.valueOf = x.valueOf;
var k = new x();
console.log(k, x); //x {valueOf: function} 20  the same!

Sure, why not? k now inherits a different valueOf function than the one of z that was logged before, but x.valueOf didn't change.

It's quite odd anyway that console.log calls own .valueOf() methods - notice that console.log is non-standard and not a reliable tool to prove anything. Better:

function x() {}
x.valueOf = function() { return 20; };
x.prototype.valueOf = function() { return 15; };
var z = new x();
z.valueOf(); // 15
x.valueOf(); // 20
x.prototype.valueOf = x.valueOf;
var k = new x();
k.valueOf(); // 20
x.valueOf(); // 20

Trying to make braceless method calls.

You might want to have a look at getters/setters.

I understand valueOf can be used for this, but same is with toString

Yes, valueOf and toString are automatically called when an object is cast to a primitive value - e.g. when using mathematical operators on it or doing concatenation with a string. The rules when exactly toValue and when toString is called are difficult; more details here.

Example:

z+x; // 35