Here is the behaviour I'm looking for:
function one(func){
func(5);
}
function two(arg1, arg2){
console.log(arg1);
console.log(arg2);
}
one(two(3)) //prints 3, 5
Can this behaviour or something similar be accomplished in javascript?
Conclusion. Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.
Parameters are specified within the pair of parentheses in the function definition, separated by commas.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.
You can always use the bind() function to pass some arguments to your function. It'll create a new function with the first argument - arg1 - equal to the value of 3 in this example:
function one(func){
func(5);
}
function two(arg1, arg2){
console.log(arg1);
console.log(arg2);
}
one(two.bind(null, 3))
You can read more about the bind() function here: MDN - Bind
Some workaround is possible
function one() {
var args = Array.prototype.slice.call(arguments);
var func = args[0];
args.splice(0, 1);
args.push(5);
func.apply(this, args);
}
function two(arg1, arg2) {
console.log(arg1);
console.log(arg2);
}
one(two, 3)
There's a problem with your syntax: function one
is expecting its single argument to be a function. Then, below, when you invoke it, you are not passing the function two
, but whatever two
returns when it's passed a single argument, probably undefined
. I don't know what specifically you're trying to accomplish but I'd recommend a little research into closures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With