« Previous entry | Next entry » Browse > Snippets

Skip to comments (8) [javascript] toClosure
Posted by Erik on Jan 20 2006 @ 15:48  :: 3851 unique visits

My post from yesterday contained an interresting toClosure function. I have improved this function a little to allow for more interresting usages such as event handlers:
CODE: JAVASCRIPT
Function.prototype.toClosure = function() {
  var f = this;
  // a Array object is needed because arguments doesn't support concat/join.
  var a = new Array(arguments.length);
  for (var i = 0; i < arguments.length; ++i) {
    a[i] = arguments[i];
  }
  return function() {
    // concat/join the 2 argument array's
    for (var i = 0; i < arguments.length; ++i) {
      a[a.length] = arguments[i];
    }
    return f.apply(this, a);
  }
}


One simple example:
CODE: JAVASCRIPT
function add(i, j) {
  return i + j;
}

var plus2 = add.toClosure(2);

plus2(3); // will return 5  (add(2, 3))
 


A simple example even handler:
CODE: JAVASCRIPT
// str is the argument given at the time the closure was created
// e is the event objects which good browsers pass to the onclick handler
function foo(str, e) {
  // do something with the event
  var button = e ? e.button : window.event.button; // for IE

  // the this keyword point to the right object so this.href works
  alert(this.href + str + button);

  return false; // don't follow the link
}

var somelink = document.getElementById('somelink');
somelink.onclick = foo.toClosure('\n foo \n');

8 comments posted so far
Add your own »

1. On Jan 20 2006 @ 17:15 l0ne wrote:

Partially applying arguments to a function, yielding a new function, is called currying in functional languages... if I'm not mistaken.

2. On Jan 20 2006 @ 17:39 Erik wrote:

That's right, I have posted things about currying before.

3. On Mar 10 2006 @ 01:42 url wrote:

here is a good article about currying with javascript :

http://www.svendtofte.com/code/curried_javascript/

4. On May 13 2009 @ 15:52 guest wrote:

Need Furniture? And need to buy furniture from China at competitive price? LongYear Furniture is your source for quality bedroom furniture featuring a huge selection of home furniture a happy home for beautiful life, kids furniture for a good memory of childhood, and to gain an extra good price from wholesale furniture and direct from  furniture manufacturers China, styles of China furniture are available, living room furniture is also nice for your house, find dining room furniture and more!

7. On Jul 14 2009 @ 04:24 guest wrote:

buy wow gold
my wow power leveling
buy wow gold
good wow power leveling
BUY wow gold
my wow power leveling
CHEAP rs gold
cheap wow power leveling
CHEAPEST lotro gold
MY aion gold
buy wow gold
cheap wow gold
CHEAPEST wow gold

Add a new comment

Name:
Password: (leave empty for anonymous comment)
 
View formatting tags Comment: