输出对象先toString再valueOf
先调用toString,若返回基础类型,则输出
var test = {
toString:function () {
console.log('toString');
return 1;
},
valueOf:function () {
console.log('valueOf');
return 2;
}
}
alert(test);
// toString
// 弹出1
若toString返回的不是基础类型,则继续调用valueOf
var test = {
toString:function () {
console.log('toString');
return {};
},
valueOf:function () {
console.log('valueOf');
return 2;
}
}
alert(test);
// toString
// valueOf
// 弹出2
若两者都返回非基础类型值,则抛出异常
var test = {
toString:function () {
console.log('toString');
return {};
},
valueOf:function () {
console.log('valueOf');
return {};
}
}
alert(test);
// toString
// valueOf
// Uncaught TypeError: Cannot convert object to primitive value
参与运算先valueOf再toString
先调用valueOf,若返回基础类型,则进行运算
var test = {
toString:function () {
console.log('toString');
return 1;
},
valueOf:function () {
console.log('valueOf');
return 2;
}
}
alert(test + 1);
// valueOf
// 弹出3
若valueOf返回非基础类型,则继续调用toString
var test = {
toString:function () {
console.log('toString');
return 1;
},
valueOf:function () {
console.log('valueOf');
return {};
}
}
alert(test + 1);
// valueOf
// toString
// 弹出2
若两者返回均为非基础类型,则抛出异常
var test = {
toString:function () {
console.log('toString');
return {};
},
valueOf:function () {
console.log('valueOf');
return {};
}
}
alert(test + 1);
// valueOf
// toString
// Uncaught TypeError: Cannot convert object to primitive value
应用
- == 比较
若对象和字符串或者数值比较,则先要将对象先转换成基础类型再进行比较var a = {a:1}; a.valueOf = a.toString = function () { return 1; } a == '1' // true
- add(2)(3)(4)
function add(arg){ var sum = arg, result = function (b) { sum += b; return result; } result.valueOf = result.toString = function(){ return sum; } return result; } add(2)(3)(4)