Here is the problem

function callback (arg) { console.log(arg); // undefined } function test(callback) { callback(); } test(callback); 

The question is how to pass arguments to the callback function?

  • what arguments need to be passed ??? - Grundy
  • test(function() { callback(1,2,3); }); - Igor
  • I do not understand what the problem is. Choice: callback ('defined'), callback.call (this, 'defined'), test (callback.bind (this, 'defined')) - Duck Learns to Hide
  • @Grundy arguments can be any absolutely - modelfak
  • one
    @modelfak, inside the test, nothing is described, there are probably no additional defined variables outside. So what exactly should be conveyed if you have nothing? - Grundy

2 answers 2

Refer to closures.

 var callback = function (a, b, c) { console.log(a, b, c); } var wrapper = function () { return callback(1, 2, 3); } var wrapperFactory = function (a, b, c) { return function () { return callback(a, b, c); }; } $element.addEventListener('click', wrapper); $element.addEventListener('click', wrapperFactory(1, 3, 2)); 

better still use magic with .call / .apply to transfer this

 var factory = function (callback) { var args = Array.prototype.slice.call(arguments, 1), self = this; // это скорее всего не нужно, просто я не кунг-фу мастер в js и не знаю, сохранится ли this return function () { return callback.apply(self, args); }; } $element.addEventListener('click', factory(callbackA, 1, 12)); $element.addEventListener('mouseup', factory(callbackB, 'long', 'argument', 'list')); 

@MorePortableUt offers an identical result with .bind :

 $element.addEventListener('click', callbackA.bind(undefined, 1, 12)); $element.addEventListener('mouseup', callbackB.bind($element, 'long', 'argument', 'list')); 
  • one
    so bind is possible without crutches, you can bind not only the context but also the arguments. Those. such a thing is already at the language level - Duck Learns to Take Cover
  • 2
    that is, $ element.addEventListener ('click', callbackA.bind (window, 1, 12)); - Duck Learns to Take Cover
  • @Morely upsetting Wow , I didn’t know, somehow missed it - etki
  • @MorelyPorotAutka on the waves of offtopic, partial application / currying is not planned in the next releases? - etki
  • As far as I understand the word "currying" - this is it, bind returns a wrapper function. Yes, if it’s es5 standard, if you have old donkeys (<= 8) or something else strange, then there isn’t out of the box. - Duck Learns to Take Cover
 //Обратитесь к аргументам данной функции. function callback (arg) { console.log(callback.arguments); } function test(callback) { //Тут передаем несколько аргументов в нашу функцию callback(1,2,3); } test(callback); //на выводе в консоли получаем [1,2,3] 
  • well at least test(callback, args) - user220409