It is commonly asked question these days in the JavaScript community: "How to structure code in a large JavaScript application?" Specifically, how to do you write code base that can draw from reusable components.
In "classical" languages, this is done through Inheritance and sub classing. You have a base class, that inherits from its super class. Since JavaScript has become popular in recent years, and being a very powerful language, this pattern has been forced event on JavaScript, creating features that are not originally there. Frameworks like ExtJS (now sencha) or dojo are an example of such structures.
JavaScript being a prototypal language, has it's own inheritance model: delegation. Here is a Wikipedia description of delegation and by the end of the article you see: "Delegation is a fundamental technique used in languages of prototype-based programming (such as JavaScript)."
One of the patterns that uses delegation is called Strategy pattern: a pattern whereby algorithms can be selected at runtime. Here is an example of JavaScript strategy pattern (taken from Wikipedia)
var Button = function(submit_func, label) {
this.label = label;
this.on_submit = function(numbers) {
return submit_func(numbers);
};
};
var numbers = [1,2,3,4,5,6,7,8,9];
var sum = function(n) {
var sum = 0;
for ( var a in n ) {
sum = sum + n[a];
}
return sum;
};
var a = new Button(sum, "Add numbers");
var b = new Button(function(numbers) {
return numbers.join(',');
}, "Print numbers");
a.on_submit(numbers);
b.on_submit(numbers);
I must admit I came to the discover of delegation backwards: I have been writing very complex frameworks, and never quite had a use for classical inheritance. At the same time working with ExtJs, and seeing how much unnecessary overhead classical inheritance brings to the JavaScript, I never left quite right using it anyway. Finally, reading more on this topic, I realized that in fact delegation is the intended way of structuring your code in prototype-based programming languages. Just as a side note, prototype-based programming languages are newer (more modern) than classical languages, and I believe more powerful.