简体   繁体   中英

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"]). 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". You can read more about apply here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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