Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Higher Order Programming in JavaScript

By Sjoerd Visscher
2006-08-18


Using methods as functions

Update: Dan Shappir pointed out to me that is useful for event handlers and callback function too. Read more about that here.

When doing higher order programming in an object oriented language, you'd want to pass methods as arguments. But there's a problem. Let's make an element class with a wrap method:

function element(tag) {

this.stag='<'+tag+'>';
this.etag='</'+tag.replace(/s.*/,'')+'>';
this.wrap=function(x) {
return this.stag+x+this.etag;
}
}

P=new element('P');
// this works:
document.write(P.wrap('This is a paragraph.'));
// this fails:
document.write(arr.reduce(P.wrap));

Why does this fail? Because when P.wrap is passed to the reduce function, only the function is passed, where this has a different meaning. But there's a little trick that makes method passing work:

function element(tag) {

this.stag='<'+tag+'>';
this.etag='</'+tag.replace(/s.*/,'')+'>';
var me=this;
this.wrap=function(x) {
return me.stag+x+me.etag;
}
}

P=new element('P');
// this still works:
document.write(P.wrap('This is a paragraph.'));
// and now this works too:
document.write(arr.reduce(P.wrap));

It looks like it's the same, but me is just a variable where this has a special meaning to every function. Javascript will make sure the wrap method will still know what me points to, no matter where the method is used.



Tutorial Pages:
» Introduction
» Generating HTML
» Using methods as functions
» When should you use this?


This article is licensed under the Creative Commons


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources