Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function with parameters as a parameter?

Tags:

javascript

People also ask

Can we pass function as parameter?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Can you pass a method as a parameter in JavaScript?

In JavaScript, passing a function as a parameter to another function is similar to passing values. The way to pass a function is to remove the parenthesis () of the function when you assign it as a parameter. In the following sections, a function pass is demonstrated as a parameter.

How do you pass a function name as a parameter in C++?

You can introduce a template parameter (here Pred ) for "anything that is callable with two parameters": template <typename Iter, typename Pred> void mysort(Iter begin, Iter end, Pred predicate) { --end; // ... if (predicate(*begin, *end)) { // ... } // ... }

Can you pass function as parameter in Python?

Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.


Use a "closure":

$(edit_link).click(function(){ return changeViewMode(myvar); });

This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.


Use Function.prototype.bind(). Quoting MDN:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

It is supported by all major browsers, including IE9+.

Your code should look like this:

$(edit_link).click(changeViewMode.bind(null, myvar));

Side note: I assume you are in global context, i.e. this variable is window; otherwise use this instead of null.


No, but you can pass one without parameters, and do this:

$(edit_link).click(
  function() { changeViewMode(myvar); }
);

So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure


Or if you are using es6 you should be able to use an arrow function

$(edit_link).click(() => changeViewMode(myvar));

Yes, like this:

$(edit_link).click(function() { changeViewMode(myvar) });