简体   繁体   English

访问回调函数参数

[英]Accessing the callback functions arguments

 function wrapper(fn) { return function(...args) { console.log(args); fn.apply(this, args); return this; } } function Person() {} Person.prototype.setName = wrapper(function (first, last) { this.first = first; this.last = last; }) Person.prototype.sayName = function () { console.log(this.first + ' ' + this.last); } const p = new Person(); p.setName('John','Doe'); p.sayName(); 

in the sample code pattern, the console statement prints the arguments passed to the "wrapper" function (which is ["john", "doe"]). 在示例代码模式中,console语句打印传递给“包装器”函数(即[“ john”,“ doe”])的参数。 My confusion is how it can read the callback functions arguments in the returned function. 我的困惑是它如何读取返回函数中的回调函数参数。 Appreciate any pointer to help in understanding this. 感谢任何有助于理解这一点的指针。

This seems unnecessarily confusing piece of code, you could achieve the same result with much less code. 这似乎不必要地使代码混乱,您可以用更少的代码来达到相同的结果。 That being said, it is because with apply you call a function (your callback function) with a given this value (which you already have) and arguments, which is an array in this case with the values of "John" and "Doe". 就是说,这是因为使用apply会调用具有给定的此值(您已经拥有)和参数的函数(您的回调函数),在这种情况下,该函数是一个数组,其中包含“ John”和“ Doe”的值。 You can read more about apply here . 您可以在此处阅读有关申请的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM