簡體   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