众所周知,如果我们需要检测对象类,我们可以使用Object.prototype.toString.call(arg)
。
但是在我的测试中,Object.prototype.toString.call(arg) === toString
。
那么,为什么我们不使用 toString.call(arg)
来替换 Object.prototype.toString.call(arg)
这是一个 long 类型。
在 Polyfill of Array.isArray
,它还使用Object.prototype.toString.call(arg)
。
different between Object.toString and Object.prototype.toString
最佳答案
这不是必需的,它只是让代码的意图更加清晰。当您使用 toString
独立函数时,通常会引用 window.toString
- window
是一个对象,并且对象继承自Object.prototype
,因此window.toString === Object.prototype.toString
。但是隐式依赖这种东西可能是 confusing并且会产生错误。
也不能保证您没有定义任何名为 toString
的其他函数,例如:
(() => {
const toString = () => 'here is a string';
// many lines of code here
class Foo {}
const f = new Foo();
// Does not result in "[object Object]":
console.log(toString.call(f));
})();
显式使用 Object.prototype.toString
可以使代码一目了然地更易于理解和预测。
(如果您愿意,您仍然可以自由地单独使用 toString
,它可能不会破坏任何东西,但总的来说这可能不是一个好主意。 )
关于javascript - Object.prototype.toString 和 toString 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57004235/