gpt4 book ai didi

javascript - 从多个构造函数调用中通用读取参数

转载 作者:行者123 更新时间:2023-11-30 08:28:41 25 4
gpt4 key购买 nike

Read arguments from constructor call 的后续问题:

接受的解决方案允许我通过定义一个包装器类来获取传递给构造函数的参数,该类捕获并公开参数,但这给我留下了一个问题,即 n 包装器用于 n 构造函数。

有没有办法让 1 个函数/包装器/任何可以为任意数量的构造函数工作的东西?

我要重申,我正在研究这项技术,专门用于测试 Webpack plugin configuration ,我想避免为我需要测试的每个插件使用单独的包装器。

寻找类似的东西

// ------------------------------------------------------------ a wrapper function?

const someWrapper = () => { /* ... */ }

const plugin1 = new Plugin({ a: 'value' })
const plugin2 = new Plugin2(arg1, arg2, { b: 'anotherValue '})

someWrapper(plugin1).args === [{ a: 'value' }]
someWrapper(plugin2).args === [arg1, arg2, { b: 'anotherValue' }]

// --------------------------------------------------------------- a wrapper class?

class Wrapper { /* ... */ }

const plugin1 = new Wrapper(Plugin, [{ a: 'value' }])
const plugin2 = new Wrapper(Plugin2, [arg1, arg2, { b: 'anotherValue '}])

plugin1.args === [{ a: 'value' }]
plugin2.args === [arg1, arg2, { b: 'anotherValue '}]

// problem with above is the wrapper is being passed to Webpack, not the underlying
// plugin; not sure yet if this would cause webpack to break or not actually
// execute the plugin as intended with a vanilla config

// ---------------------------------------------------------------- something else?

最佳答案

是的,您可以创建通用包装器,它将 args 属性添加到任何传递的构造函数的实例:

class Plugin {
constructor (arg1, arg2) {
this.arg1 = arg1
this.arg2 = arg2
}
}

function wrapper(initial) {
// Rewrite initial constructor with our function
return function decoratedContructor(...args) {
// Create instance of initial object
const decorated = new initial(...args)

// Add some additional properties, methods
decorated.args = [...args]

// Return instantiated and modified object
return decorated
}
}

const decoratedPlugin = wrapper(Plugin)
const plugin = new decoratedPlugin('argument', { 'argument2': 1 })
console.log(plugin.args)

仅供引用:添加没有前缀的属性是不安全的。考虑将 __ 或类似的内容添加到您的属性中,因为您可能会不小心重写某些内部对象属性。

关于javascript - 从多个构造函数调用中通用读取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com