0

As we know, we can use the Object.prototype.toString.call(arg) if we need to detect object class.

But In my test, Object.prototype.toString.call(arg) === toString.

So, why don't we use toString.call(arg) to replace Object.prototype.toString.call(arg) which is a long type.

In the Polyfill of Array.isArray, It also use Object.prototype.toString.call(arg).

different between Object.toString and Object.prototype.toString

1
  • 3
    These are totally different methods. instance.toString gives a string presentation of the instance of an object, and is often overridden. And as you've noticed, calling Object.prototype.toString gives a "Class" of the object. For example, consider the return values of [].toString() and Object.prototype.toString.call([]); ... Commented Jul 12, 2019 at 9:39

1 Answer 1

4

It's not necessary, it just makes the code's intent more clear. When you use the toString standalone function, usually that'll refer to window.toString - window is an object, and objects inherit from Object.prototype, so window.toString === Object.prototype.toString. But relying on this sort of thing implicitly can be confusing and can produce bugs.

There's also no guarantee that there's not some other function you've defined called toString, eg:

(() => {
  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));
})();

Explicitly using Object.prototype.toString instead makes the code more understandable and predictable at a glance.

(You're still free to use toString alone instead if you want, it probably won't break anything, but it's probably not a great idea in general.)

Sign up to request clarification or add additional context in comments.

5 Comments

Why do you use an IIFE here?
@Kobe To avoid polluting the global namespace.
Not that important, it just distinguishes the locally scoped toString from the toString visible on the top level, though even if it was on the top level, It doesn't overwrite window.toString if it's declared with const. It doesn't really matter, just slightly reduces the possibility of confusion from looking at the snippet
And window.toString might not necessarily be Object.prototype.toString (or does the Web Spec say that?) ...
@JonasWilms Yeah, could be, that's why I said usually. window.toString is writable, it's not even a property of window, it's just inheriting from Object.prototype

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.