valueOf和toString方法
let a = {
toString: fucntion() {
return '1'
},
valueOf: function() {
return 2
}
}
console.log(a + 3)
猜猜结果是多少?离谱!!!结果是 5
let a = {
toString: fucntion() {
return '1'
},
}
console.log(a + 3)
离谱!!!结果是4
函数的toString方法
function add(x, y) {
return x + y
}
console.log(add.toString()) // 输出结果为函数字符串
console.log(add.bind().toString()) //输出结果为 function () { [native code] }
由于bind()方法是用c++实现的原始方法,所以不能获取到其真实的代码字符串
(function(x) {
return function(y) {
return x + y
}
})(42).toString();
// 输出结果
"function(y) {
return x + y
}"
x是一个固定值为42的闭包,但是toString()方法并不能真实的反应出这种状态。