繁体   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(); 

在示例代码模式中,console语句打印传递给“包装器”函数(即[“ john”,“ doe”])的参数。 我的困惑是它如何读取返回函数中的回调函数参数。 感谢任何有助于理解这一点的指针。

这似乎不必要地使代码混乱,您可以用更少的代码来达到相同的结果。 就是说,这是因为使用apply会调用具有给定的此值(您已经拥有)和参数的函数(您的回调函数),在这种情况下,该函数是一个数组,其中包含“ John”和“ Doe”的值。 您可以在此处阅读有关申请的更多信息。

暂无
暂无

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

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