zhang xue
zhang xue

Reputation: 1

toString and valueOf Execution order make me confused

the object f string conversion, but not call the prototype chain toString method

function fn(){}

fn.prototype.toString = function(){
    console.log("toString call");
    return {};
}
fn.prototype.valueOf = function(){
    console.log("valueOf call");
    return 100;
}

let f = new fn();
console.log("before "+f+" after"); 

// I hope:toString call --> valueOf call --> 'before 100 after'
// Result: valueOf call --> 'before 100 after'

Upvotes: 0

Views: 58

Answers (1)

Hao Wu
Hao Wu

Reputation: 20867

Try

console.log(`before ${f} after`);

When using + (addition or string concatenation), the hint parameter that passed to [Symbol.toPrimitive](hint) is default, which will call valueOf() by default.

But when using template string, the hint would be string, so toString() will be called first.

function fn(){}

fn.prototype.toString = function(){
    console.log("toString call");
    return {};
}
fn.prototype.valueOf = function(){
    console.log("valueOf call");
    return 100;
}

let f = new fn();
console.log(`before ${f} after`); 

Upvotes: 0

Related Questions