将变量注入到匿名函数中



是否可以在不将变量作为参数传入或不将其放入全局范围的情况下,将变量注入到命名函数中?也就是说,我正在寻找是否可以做类似的事情:

/** 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 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 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)) 

最新更新