Javascript - add parameters to a function passed as a parameter

纵然是瞬间 提交于 2019-12-01 03:58:17

问题


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?


回答1:


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)



回答2:


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




回答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.




回答4:


function one(arg){
   two(arg, 5); // func here is two so it requires two params...
}

function two(arg1, arg2){
   console.log(arg1);
   console.log(arg2);
}

one(3)// one expect function so can't execute function here!



回答5:


as soon as one expects function as argument two(3) should return function.
this condition is required so in order to achieve it your two function should be

function two(arg1){
    console.log(arg1);
        return function(arg2) {
        console.log(arg2);
    };
}

so two(3) function call gets passed as argument to one
so before assigning value to variable engine executes it. And execution of two(3) call logs 3 to console and returns function

   function(arg2) {
      console.log(arg2);
    };

and then engine assigns executed value(returned function) to func variable. so func parameter of one function now looks like

func = function(arg2) {
    console.log(arg2);
 };

one calls func with 5 passed in as argument. so 5 gets logged to console.




回答6:


Basically you can't specify the parameter in the function or it'll run. You need to specify the function aka one(two), but that obviously wouldn't work.

However if you dynamically create a function you should be able to accomplish the task like so :

function one(func){
   func(5);
}

function two(arg1, arg2){
   console.log(arg1);
   console.log(arg2);
}

one(function(val) { two(3, val) }) //prints 3, 5


来源:https://stackoverflow.com/questions/42002334/javascript-add-parameters-to-a-function-passed-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!