I am having some trouble wrapping my head around this function:
var toStr = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]
How does this function accept an argument as seen in line 2?
Well,
Function.prototype.callreferences the “call” function, which is used to invoke functions with chosenthisvalues;.bindrefers to the “bind” function on the Function prototype (remember: “call” is a function too), which returns a new function that will always havethisset to the passed-in argument.thisset to the “toString” function.The result, therefore, is like this code:
Object.prototype.toString.call( param ). Then, the “console.log” call passes that function an array, and there you have it.edit Note that
Object.prototype.toString.call( param )is likeparam.toString()really, when “param” is an object. When it’s not, then the semantics of the “call” function are to turn it into one in the normal ways JavaScript does that (numbers -> Number, strings -> String, etc).edit, 24 May2016 — That last sentence above is not accurate with ES2015. New JavaScript runtimes do not “autobox” primitive types when those are involved with a function call as a
thisvalue.