0

lot of times when passing function by reference in javascript usually to events i have to write:

something.onclick = function(){
    callback(3);
};

but i rather always want to do this:

something.onclick = callback...put parameters here

so basically i always wanted to pass reference to a function along parameters so it won't get executed right away.

Recently after thinking and looking around i made this..

Function.prototype.pass = function(){
   var args=arguments, func = this;
   return function(){ func.apply(this,args);}
};

now i can just add callbacks without writing placeholder functions like this:

eleA.onclick(logWhichEle.pass('A'));
eleB.onclick(logWhichEle.pass('B'));
eleC.onclick(logWhichEle.pass('C'));

when i was new i tried to do this even though i knew it won't work i was hopping it would somehow..

eleA.onclick(logWhichEle('A'));

but that just returned undefined.

So is doing solution above unsafe..what can i do further to make it safer. Like not unintentionally break someone's code.

Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • 2
    What you are doing here is called "partial application". [Here](http://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications) is a question discussing various approaches to it and why it is useful. – Russell Zahniser Apr 15 '14 at 02:37
  • there is some problem here it only works for functions declared as `function abc(){}`, and not functions inside objects like `obj.func.pass()`..`this` gets set to func itself instead of obj. – Muhammad Umer Apr 15 '14 at 18:03

1 Answers1

2

You can also avoid affecting Function prototype. The approach would be like this:

function callbackWrapper() {
    var args = Array.prototype.slice.call(arguments, 0), fn = args.shift();
    return function() { return fn.apply(null, Array.prototype.concat.apply(args, arguments)); };
}

var adderTo1 = callbackWrapper(function(a, b) { return a + b; }, 1);
alert(adderTo1(2));
leandroico
  • 1,207
  • 13
  • 17