Borrowing methods pattern

Functions in JavaScript are objects, they come with some cool methods of their own, like call() and apply(). The only difference between both is that one takes an array of parameters, the other one takes parameters one by one.

And you can use these methods to borrow functionality. Here's how:

// call() example, param1, p2, p3);
// apply() example
notmyobj.doStuff.apply(myobj, [param1, p2, p3]);

So your object is called myobj and you know some other object called notmyobj has an extraordinary useful method called doStuff().
Instead of going through the inheritance hassle and inherit a bunch of stuff you donít need, you can simply borrow the method you like temporarily.

You pass your object and any parameters and the other binds your object as its own this. Basically you pretend to be the other object, benefit from the method you like and move on.

Itís like getting an inheritance but without paying the inheritance tax. Where tax that comes in the form of useless properties.

Example: borrow from Array

A common use for this pattern is borrowing array methods.

Arrays have useful methods which array-like objects such as arguments do not. So arguments can borrow methods, like the slice() method.

function f() {
   var args = [], 1, 3);
   return args;
// example
f(1, 2, 3, 4, 5, 6) // return [2,3]

In the example above, thereís an empty array created just for the sake of using its method.
A slightly longer way to do the same is to borrow the method from the Array.prototype directly. This saves creating one empty array.

Tags: ,

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile you can find me on twitter - @stoyanstefanov