How do return object properties work in JavaScript?

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]. It makes sense to me because they are objects. But this modified 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 think that to obtain such a result would require foo.valand boo.val. I would also think what would valueOfneed to be called so that it could affect the return values.

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

, / , , . !

+4
3

: "JavaScript valueOf ". () valueOf(), , .

:

, valueOf , :

[ ]

+3

.valueOf(), val. +.

, "ToNumber", . , , valueOf , . .

0

, . , . .

:

ToPrimitive 5 6. . ECMAScript, Date, , ...

JavaScript- Objects to Number a b:

  • valueOf.
  • ( ), .
    • toString, [object Object]
  • .

, var foo = new Foo("2"); , . , Foo.prototype.toString = ..., , .

0

All Articles