Blog
Blog copied to clipboard
对象的隐式转换
对象也可以被强制转换为原始值。最常见的用法就是转换为字符串:
alert("Math 对象:"+Math) ; // "Math 对象: [object Math]"
alert("JSON 对象:"+JSON) ; // "JSON对象: [object JSON]"
对象通过隐式的调用toString方法转换为字符串。你也可以通过调用对象的toString方法进行验证:
alert(Math.toString()) ; // " [object Math]"
alert(JSON.toString()) ; // "[object JSON]"
当然对象也可以通过valueOf方法转换为数字:
"string : "+{ toString:function () { return "Ychow Xiao" } } ; // "string : Ychow Xiao"
2 * { valueOf :function () { return 5 }}; // 10
当一个对象同时包含toString和valueOf方法时,运算符 + 这种应该调用哪种方法其实并不明显。是做字符串拼接,还是加法运算,这还得根据参数的类型。如果你没有明确指出偏好哪一种,JavaScript就会根据自己的喜好,去选择valueOf !!!
var obj={
toString:function(){
return "Hello Ychow Xiao";
},
valueOf:function(){
return 2222;
}
};
console.log("到底是谁 "+ obj)