如何在ECMAScript 6中将构造函数参数传递给导入的类? [英] How do I pass constructor parameters to imported class in ECMAScript 6?

查看:78
本文介绍了如何在ECMAScript 6中将构造函数参数传递给导入的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要将类导入其他脚本,如何使用ES6语法将参数传递给该类构造函数?

If I'm importing a class into some other script, how can I pass parameters to that class constructor in ES6 syntax?

我想做这样的事情.我已经看到了诸如包装函数或使用工厂模式之类的各种建议,但是有没有更简洁的方法呢?

I would like to do something like this. I've seen various suggestions like wrapping functions or using factory pattern, but is there a cleaner simpler way of doing this?

// This is sudo code
import SomeClass from './SomeClassPath';
var thing = SomeClass(params);

推荐答案

我看到您的问题有些困惑,所以让我澄清一下.

I see that there is some confusion in your question, so let me clarify.

在ES6中,当您需要导出模块时,您可能知道有两种策略.您可以使用默认导出多个导出.让我们举一个非常基本的示例(围绕console的简单记录器):

In ES6, you may know that you have two strategies when you need to export a module. You can use a default export or multiple exports. Let's take a very basic example (a simple logger around console):

function info(msg) {
  console.info(`[Info] ${msg}`);
}

function error(msg) {
  console.error(`[Error] ${msg)`);
}

默认导出

在这里,我们必须对功能进行分组.在JavaScript中,最惯用的方法是使用对象文字(请参见显示模块模式):

export default {
  info(msg) {
    console.info(`[Info] ${msg}`);
  },
  error(msg) {
    console.error(`[Error] ${msg}`);
  }
};

然后,在我们的客户代码中,我们将像下面这样使用此模块:

Then, in our client code, we will use this module like so:

import logger from './logger'

logger.info('Hello!');
logger.error('Oops!');

多个出口

在这里,我们可以独立导出函数:

Multiple exports

Here we can export our functions independently:

export function info(msg) {
  console.info(`[Info] ${msg}`);
}

export function error(msg) {
  console.error(`[Error] ${msg}`);
}

然后,在我们的客户代码中,我们将像下面这样使用此模块:

Then, in our client code, we will use this module like so:

import {info, error} from './logger'

info('Hello!');
error('Oops!');

完成.

我建议您了解ES6模块系统如何与我们的功能示例一起工作.与类完全相同...

I suggest you to understand how the ES6 module system works with our functional example. It is exactly the same thing with classes...

通过阅读评论,我看到了另一个需要澄清的混乱:单一.

By reading the comments, I have seen another confusion that requires clarification: the Singleton.

Singleton是一种设计模式,可以仅一次一次实例化一个类.现在想象一下我们的课程如下:

Singleton is a design pattern that makes it possible to instantiate a class just once. Now imagine that our class is the following:

export default class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
};

我们可以这样使用它:

import Person from './Person';

let me = new Person('Baptiste', 'Vannesson'),
    you = new Person('David', 'Choi');

console.log(Object.is(me, you)); // false, so there are two instances of Person
console.log(me.firstName, me.lastName);  // Baptiste Vannesson
console.log(you.firstName, you.lastName); // David Choi

如您所见,Person与Singleton无关!它将是具有以下Java启发性实现的Singleton:

As you can see, Person has nothing to do with Singleton! It would be a Singleton with the following Java-inspired implementation:

export default (() => {

  class Person {
    // Private constructor
    constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }
  }

  return {
    // Public static factory method
    getInstance(firstName, lastName) {
      if (!Person.instance) {
        Person.instance = new Person(firstName, lastName);
      }
      return Person.instance;
    }
  };

})();

客户代码:

import Person from './Person';

let me = Person.getInstance('Baptiste', 'Vannesson'),
    you = Person.getInstance('David', 'Choi');

console.log(Object.is(me, you)); // true, so there is only one instance
console.log(me.firstName, me.lastName); // Baptiste Vannesson
console.log(you.firstName, you.lastName); // Baptiste Vannesson (still me!)

为简单起见,您可能希望直接导出实例:

For the sake of simplicity, you may prefer to export an instance directly:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
};

export default new Person('David', 'Choi');

客户代码:

import person from './person';

// Person is not a constructor but a simple instance
let me = person,
    you = person;

console.log(Object.is(me, you)); // true
console.log(me.firstName, me.lastName); // David Choi
console.log(you.firstName, you.lastName); // David Choi

如果这样做,使用对象字面量甚至会更简单:

If you do that, this would be even simpler to use an object literal:

export default {
  firstName: 'David',
  lastName: 'Choi'
};

客户端代码在这里不变.

The client code does not change here.

这篇关于如何在ECMAScript 6中将构造函数参数传递给导入的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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