I can not understand why in this function to use the Object.prototype in order to check the input and determine whether it is a String ? What is the difference between using Object.prototype.toString.call(input) and using toString.call(input) ?

 var isString = function (input) { // Почему здесь используют Object.prototype, // когда можно просто использовать метод toString.call(input) ? if (Object.prototype.toString.call(input) === '[object String]') { return true; } else { return false; } } console.log(isString('w3resource')); console.log(isString([0, 1, 2, 4])); console.log(isString({name: "Nureke", age: 24})); 
  • it is better to use typeof here - Grundy
  • if(typeof input == 'string') return true?true:false; else return false?true:false; - vp_arth

1 answer 1

Normally, descendants override toString from the object.
These are essentially different methods.

For example, Array.prototype.toString collects the elements of an array separated by commas.
And Object.prototype.toString using internal witches, determines the type and displays it in a certain format.

That is, if you need to determine the type, we take the object's prototype method and, of course, set this , without it, the object will not be expected to work.

toString.call(input) === Object.prototype.toString , so calls are usually equivalent (thanks to @Grundy for editing).
However, if someone does var toString = 42; in the global area, but will be bad.

PS Why if ? The comparison already returns a boolean value.

  • one
    in the global scope, methods are taken from the window object, so calling toString.call(input) equivalent to window.toString.call(input) . In turn, Object.prototype.toString === window.toString . - Grundy
  • I did not know, thanks for the information. - user207618