4

The code

var Foo = function(value) {
  this.val = value;
}

var foo = new Foo(2);
var boo = new Foo(3);
return foo+boo;

returns [object Object][object Object]. This makes sense to me because they are objects. But this amended version of the code returns 5:

var Foo = function(value) {
  this.val = value;
}

Foo.prototype.valueOf = function() {
  return this.val;
}

var foo = new Foo(2);
var boo = new Foo(3);
return foo+boo;

Why? I would have thought that foo.val and boo.val would be required to produce such a result. I would have also thought that valueOfwould need to be called in order for it to have any effect on the returned values.

I have looked at some JavaScript documentation pertaining to valueOf() at Mozilla Developer Network (it was recommended reading for this problem), but I still don't understand what's going on here. (Side note: I also don't understand how a function can be called without the parentheses following it...)

I am looking for an answer that explains some of the underlying mechanics/processes of objects while still being accessible to someone who is new to objects. Thanks!

4
  • In the second instance you're redefining what valueOf() returns. By default on objects, valueOf() returns [object Object]. You can also redefine toString() for other interesting results when concatinating into a string. Commented Apr 10, 2015 at 21:10
  • @PatrickGunderson So, to clarify, the amendment redefines the method object.valueOf() that every object already has? Commented Apr 10, 2015 at 21:45
  • @QueenCode that is Correct. Commented Apr 10, 2015 at 21:50
  • + can call valueOf or toString or both. Which one is called first depends on the type of object. Commented Apr 10, 2015 at 22:16

2 Answers 2

3

That's easy: "JavaScript calls the valueOf method to convert an object to a primitive value." (more info) You are defining valueOf(), which is called upon to provide a value for an object when used in an operation.

It goes on to say:

If an object has no primitive value, valueOf returns the object itself, which is displayed as:

[object Object]

Sign up to request clarification or add additional context in comments.

Comments

0

You gave your constructor's prototype a .valueOf() function that returns the val property. That function is what's consulted by the operation of the + operator.

When neither operand is a string, the innards call an internal "ToNumber" function to get the operand values. That, in turn, will try the valueOf function on object values if it exists. In your case, it does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.