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!
valueOf()returns. By default on objects,valueOf()returns[object Object]. You can also redefinetoString()for other interesting results when concatinating into a string.object.valueOf()that every object already has?+can callvalueOfortoStringor both. Which one is called first depends on the type of object.