[英]How can I get the arguments for function that I pass as a parameter to another function?
我正在嘗試從作為參數傳遞的函數中訪問參數,以確保傳遞這些參數,但是我遇到了錯誤:
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'))()
可以做到,但並不完美。 您必須從傳遞的函數中返回帶有所需參數的對象
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"));
我猜您正在嘗試執行的操作是使用“日志記錄”功能攔截某個功能。
如果是這樣,則有另一種方法使用ES6 rest參數-
let withLog = func => (...args) => {
console.log(...args);
return func(...args);
};
let add = (x, y) => x + y;
withLog(add)(2, 3); // outputs '2 3', returns 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.