toString 和 valueOf 执行顺序让我很困惑[重复]

问题描述 投票:0回答:1

将对象f进行字符串转换,但不调用原型链的toString方法

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'

javascript tostring value-of
1个回答
0
投票

尝试

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

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'

© www.soinside.com 2019 - 2024. All rights reserved.