从构造函数调用中读取参数 [英] Read arguments from constructor call

查看:118
本文介绍了从构造函数调用中读取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

const anInstance = new Plugin({ a: 'path' })

您能否返回给出的参数?

Can you return the arguments given?

anInstance./* some method */ === [{ a: 'path' }]

// or

someWrapper(anInstance) === [{ a: 'path' }]

限制条件:


  1. 您无法更改插件的内部实现:视为外部依赖。

  2. 插件可能有多个参数,任何类型。

  3. 您不能将初始参数分配给外部变量,例如所以:

  1. You cannot change the internal implementation of Plugin: treat as an external dependency.
  2. Plugin may have more than one argument, of any type.
  3. You cannot assign the initial arguments to an external variable, like so:

const config = { a: 'path' }
const anInstance = new Plugin(config)







背景:我正在尝试为webpack插件配置编写测试。例如:


Background: I'm trying to write a test for a webpack plugin configuration. For example:

module.exports = {
  plugins: [
    new wepback.DllPlugin({
      name: '[name]',
      path: path.join(buildDir, '[name].json'),
    })
  ]
}

我想测试给DllPlugin的配置。上面的限制#3是因为我不想导出每个插件的配置,因为该导出的唯一消费者将是我的测试。

I want to test the configuration given to the DllPlugin. Restriction #3 above is there because I don't want to have to export the config for each plugin when the only consumer of that export would be my test.

如果有的话没办法做我最初的问题,那么我将不得不添加那些导出,因为我想不出任何其他方式来访问这些参数。

If there's no way to do my initial ask, then I'll have to add those exports, as I can't think of any other way to access those arguments.

推荐答案

您可以定义,使用 extend

function Plugin() {}

class getPluginArgs extends Plugin {
  constructor(...args) {
    super();
    this.args = args;
    for (let arg of args) {
      console.log(arg)
    }
  }
  getArgs() {
    return this.args;
  }
}

const anInstance = new getPluginArgs({ a: "path" });
console.log(anInstance instanceof Plugin, anInstance.getArgs());

这篇关于从构造函数调用中读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆