JavaScript Prototype Functions

AKA "instance methods"!

Constructor functions (any function you call with new) in JavaScript have a prototype property, which you can decorate with functions and other arbitrary values. When instantiating an object, these functions become instance methods. When calling a "method" (for instance, JavaScript will find the function is pointing to, set the context to foo (so bind this to whatever foo references for the duration of the function call) and execute the function body. JavaScript also binds local variables for each named parameter, assigning any arguments positionally, probably when the context is bound.

You can also pass functions (and other properties) around just like any other object, meaning you can assign a prototype function (or "method") to a local variable: var map = [].map;. Prototype functions typically make use of the context object, so if you create a reference to a prototype function like map, you will probably need to explicitly pass in a context object. Here's some ways you can do that:

// using apply. note the array around arguments
var map = [].map;
map.apply([ 1, 2, 3 ], [ n => n * n ]);
// using call
var map = [].map;[ 1, 2, 3 ], n => n * n);
// using bind
var map = [].map;
map.bind([ 1, 2, 3 ])(n => n * n);
// using bind, but earlier
var boundMap = [].map.bind([ 1, 2, 3 ]);
boundMap(n => n * n);
// using normal JavaScript. just do this unless you know you have a
// good reason to do one of the others
[ 1, 2, 3 ].map(n => n * n);