如何获取作为参数传递给另一个函数的函数的参数?

时间:2018-05-18 18:55:07

标签: javascript

我正在尝试从作为参数传递的函数中访问参数,以确保通过它们,但是我收到了错误:

  

TypeError:严格模式函数或调用它们的参数对象可能无法访问'caller','callee'和'arguments'属性

如何获取func的参数,以便在调用时可以传递消息?

更新:也许更好的问题是为什么我无法记录func.arguments

function a(func){
  console.log(func.arguments)
  return function(){
    func.apply(null, func.arguments);
  }
}

function log(message){
  console.log(message)
}

a(log.bind('hello'))()

2 个答案:

答案 0 :(得分:0)

它可以完成,但它不漂亮。你必须从你传递的函数返回一个带有你想要的参数的对象

function a(func){
    console.log(func.arguments)

    //you dont actually need this since you have already called the function before passing
    //return function(){
    //   func.apply(null, func.arguments);
    //}
}


function log(message){
    console.log(message);
    return {
        arguments : arguments //store the arguments and return them
    }; 
}

//you not actually passing the function here (the way you have it written)
//you are calling it and returning its value
//we return { arguments: arguments } so the "a" function can retrieve its properties.
a(log("hello")); 

答案 1 :(得分:0)

我猜你要做的是用“日志记录”功能拦截一个函数。

如果是这样,有一种不同的方法,使用ES6休息参数 -

window.open('http://www.google.com', '_blank').focus();
相关问题