JavaScript Function Context Incorrect

Context in Javascript is always established by the way you call a function.

var fn = ''.toUpperCase.call

This assigns the prototype implementation of the call function to fn. If you now call fn(), there’s no context to the call. call would try to invoke the function object it was associated with. However, that context is established at call time. Since you’re not giving it any context at call time, some internal component of call is throwing an error.

You’d have to do this:

fn.call(''.toUpperCase)

That’s right, you call the call function, establishing a context, namely the toUpperCase string function. In this specific case this would lead to another error inside toUpperCase, since it is not bound to a specific context. You’d need to establish that context explicitly as well:

var fn = ''.toUpperCase.call
fn.call(''.toUpperCase.bind(''))

Also see How does the “this” keyword work?

Leave a Comment

tech