Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active March 30, 2023 01:59
Show Gist options
  • Save cowboy/4477847 to your computer and use it in GitHub Desktop.
Save cowboy/4477847 to your computer and use it in GitHub Desktop.
JavaScript: call invo-cursion?
// OOP
console.log( 'OHAI'.blink() );
// Call invocation
console.log( String.prototype.blink.call('OHAI') );
// $ always makes things look awesome.
var $ = Function.prototype.call;
// Very explicit call invocation
console.log( $.call(String.prototype.blink, 'OHAI') );
// Very, very explicit call invocation, ie. call invo-cursion?
console.log( $.call($,$,$,$,$,$,$,$,$,$,$,$, String.prototype.blink, 'OHAI') );
// ^^^^^^^^^^^^^^^^^^^^^^^ "bonus" calls
// You can have fun with apply invocation and _ too.
var _ = Function.prototype.apply;
// Very, very explicit apply invocation, ie. apply invo-cursion.
console.log( _.apply(_,[_,[_,[_,[_,[_,[_,[_, [ String.prototype.blink, ['OHAI'] ]]]]]]]]) );
// ^^^^^^^^^^^^^^^^^^^^^^ "bonus" applies, and fun w/brackets ^^^^^^^^
@haocong
Copy link

haocong commented Sep 7, 2016

@jackocnr For the last FYI, I thought it would be like this: when you pass Number.call(or Function.call) to Array.prototype.map, the Number.call(or Function.call) is no longer an Object method, it is now just a simple function, with the call missing this then JavaScript runtime call an undefined function and will throw an error.

Array.apply(null, {length: 5}).map(Number.call) // TypeError: undefined is not a function

For better understanding, here is another example:

var call = Function.call;
call() // TypeError: call is not a function
call.call(Number, undefined, 1) // 1
call.call(String, undefined, 'foo') // foo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment