簡體   English   中英

將每個子函數的上下文綁定到父 function

[英]Bind every child function's context to parent function

假設我有一個父 function 調用一些這樣的子函數:

 function parentFn() { API.greet(); } parentFn.name = 'john'; const API = { greet: function() { console.log(`Hi there ${parentFunc.name}`); // prints out 'Hi there undefined' } }; parentFn()

無論如何,在不向內部 function 添加參數的情況下,是否可以在 API 中獲取父級 function 的屬性?

有兩種情況:

  • 每個“子”function 只能有一個“父”。 如果是這樣,只需直接引用該特定父級: parentFn.name
  • 每個“孩子” function 都可以被多個其他人調用。 在這種情況下,您需要動態值的參數。

請注意,如果您不想聲明顯式參數, this可以使用每個function和方法都有的隱式參數。 It normally points to the API object in a API.greet() call, but you can change it like API.greet.call(parentFn) (although this is slightly weird).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM