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

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

问题描述

给定

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

你能返回给定的参数吗?

Can you return the arguments given?

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

// or

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

限制:

  1. 您不能更改Plugin 的内部实现:将其视为外部依赖项.
  2. Plugin 可以有多个参数,任何类型.
  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.

推荐答案

可以定义一个class,使用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天全站免登陆