On the problem of obj addition in js

I saw

when I was watching the addition section (P48) of elevation 3 today.

clipboard.png

mention

if an Operand is an object. The toString method is called to get the corresponding string value.

I just tried the following code

var bbb = {
  i: 10,
  toString: function() {
    console.log("toString");
    return this.i;
  },
  valueOf: function() {
    console.log("valueOf");
    return this.i;
  }
}

bbb + 1// valueOf 11
bbb + "1" // valueOf 101

Why instead of toString as I expected, valueOf was executed. Did I get it wrong?


that's because you valueOf is directly a basic type, so you don't need toString .
if you change it like this, you will find that you will first valueOf , and then you will toString .

  valueOf: function() {
    console.log('valueOf');
    return this;
  }

the toString () method here is not the method in this instance obj
is the method of Object prototype
Object.prototype.toString ()
https://developer.mozilla.org.

Menu