Posts Tagged ‘Code reuse patterns’

Borrowing methods pattern

Monday, September 14th, 2009

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
notmyobj.doStuff.call(myobj, 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 = [].slice.call(arguments, 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.

Array.prototype.slice.call(...)

A case against inheritance

Monday, September 14th, 2009

Provocative title, right? Good. The point is not that inheritance is all that bad, it's that you should stop and think or a moment before you jump into long inheritance chains and complex UML.

In fact, the Object-Oriented Design Patterns book from "the gang of four" has this to say about inheritance:

“Prefer object composition to class inheritance”

It’s pretty easy to follow this advice in JavaScript. Remember - no classes in JavaScript. And how about the object literal, how simple it is? If you can add functionality to your objects from elsewhere – why do you need inheritance.

You can start with a blank slate and add stuff – either implement it yourself or grab from someone else.

Keep your eyes on the prize. You don’t need inheritance, you need functionality. In other languages inheritance may be your only choice. Not in JavaScript.

Further blog posts will show patterns such as borrowing methods, copying properties, mixins...