JavaScript

JavaScript: ValueOf an Object?

Every object in JavaScript inherits a valueOf() method from Object.prototype. But when we say obj.valueOf(), what exactly do we mean, the value of an object?

In the most simple cases, if our objects look like this:

var obj = {"a": 1, "b":2};

And we try to call x.valueOf() on them, they would return themselves, exactly as is. But, sadly, this is hardly useful.

The real fun comes when we slide deeper down the bunny hole of Object-Oriented-ness [1].

Say we have a Bunny class, and a fresh bunny:

function Bunny(name, age) {
  this.name = name;
  this.age = age;
}

var bunny = new Bunny("Ben", 0);

If we try to summon the value of this bunny now, JavaScript would try to chuck the whole object at us. Because, what exactly is the value of a bunny? Name, age, or what? JavaScript doesn’t know.

That’s why we can dictate them all. Because:

Objects are coerced into primitive values with either valueOf or toString depending on context [2].

What are those context? To give you a list:

Default valueOf() Context

  • anything with a seeming intention to calculate, e.g.
    •  obj * 3
    •  1 + obj
    • +obj

Default toString() Context

  • alert(obj)
  • ["a", obj].join(" ")

Note that the operator + is default to be taken as a calculation, so the result of valueOf() would be presented, no matter what string is sitting on the other end of it. Therefore, taking advantage of this system, we can assign our own definitions to both:

Bunny.prototype.toString = function() {
  return this.name;
};
Bunny.prototype.valueOf = function() {
  return this.age;
}

console.log(bunny.toString() + "'s age is " + bunny);
// "Ben's age is 0"

Have fun being the overlord of objects.

Standard