[英]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.