簡體   English   中英

將變量注入匿名 function

[英]Injecting a variable into an anonymous function

是否可以將變量注入匿名 function 而不將其作為參數傳遞,或者不將其放置在全局 scope 中? 即我正在尋找是否可以做類似的事情:

/** example 1 */
class A extends Array{
  constructor(...args: any){
    super(...args) // `super` exists here, even though it is not passed in as a parameter
  }
}

/** example 2 */
function B(){
  console.log(arguments) // `arguments` exists here, even though it is not passed in as a parameter
}

以下是我想要實現的一些偽代碼。

const fn1 = (supVal:string)=>{
  // can one inject `magicHiddenVariable` into `fn` below, without passing it in as a parameter?
  const magicHiddenVariable = supVal 
  return (fn:(...args: any)=>any)=>fn()
}

const usageExample = fn1('hello')
// `magicHiddenVariable` should be accessible here with 'hello'
usageExample(()=>console.log(magicHiddenVariable)) 

我不要求以下解決方案:

let  magicHiddenVariable3:string 
// `magicHiddenVariable3` is now available to all functions within its closure.
// however this is not the solution
// I'm after, as it's not limited to the scope of fn2
const fn2 = (supVal:string)=>{
  magicHiddenVariable3 = supVal 
  return (fn:(...args: any)=>any)=>fn()
}
const usageExample2 = fn2('hello')
usageExample(()=>console.log(magicHiddenVariable3))

代碼

一種方法是使用帶有返回 ref 的模塊化 function。

function useIt(supVal) {
   const magic = {value:supVal}
   const fn1 = (...args:any)=>{
     magic.value = args
   }
   return {fn1,  magic}
}


const {fn1, magic} = useIt('bar')
fn1('aVal')
console.log(magic.value)
fn1('aVal2')
console.log(magic.value)

fn1(()=>console.log(magic.value)) 

您也可以將值放入 function 本身。

function useIt(supVal) {
   const fn1 = (...args:any)=>{
     const fn1.magic = args
   }
   return fn1
}
const fn1 = useIt('bar')
fn1('aVal')
console.log(fn1.magic)
fn1('aVal2')
console.log(fn1.magic)

fn1(()=>console.log(fn1.magic)) 

暫無
暫無

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

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