先上代码
//当对象直接调用这两个方法的时候,他们的返回结果是一样的
//结果都是 [object Object]
var o = {};
console.log(o.toString());//=>[object Object]
console.log(o.toLocaleString());//=>[object Object]
//但是当以call()的方式调用的时候,他们的返回结果发生了改变
function foo () {
return true;
}
console.log(Object.prototype.toLocaleString.call(foo));//foo函数转换成了字符串
console.log(Object.prototype.toString.call(foo));//=>[object Function]
//而直接用foo调用toString()时,和通过call()调用Object.prototype.toLocaleString()返回的结果一样
console.log(foo.toString());//foo函数转换成了字符串
请问哪位能帮忙讲解下,这其中的原理?
为什么同样是调用Object.prototype对象的toLocaleString()和toString(),用在对象上和函数上却这样的差异?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你看有一个被重写了。
tostring()方法是直接转换成字符串,tolocalstring()方法是转化成带有本地格式的字符串。最好的例子就是new 一个Date对象,然后分别tostring 和tolocalstring一下,打印出来,你一看便知
楼上 scort 的答案已经回答得很好了。
根据MDN - toLocaleString, 内置对象override了toLocaleString的只有Array,Number和Date。
所以,对于这三种对象,toLocaleString 的结果也 可能 会不同。
在我的Chrome下试了一下: