ES6类和类实例作为构造函数中的参数 [英] ES6 class and class instance as parameter in constructor

查看:345
本文介绍了ES6类和类实例作为构造函数中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类A需要类B的实例. 我应该在A构造函数中创建B实例,还是在启动类A的情况下创建实例并将实例传递给A构造函数?

class A needs instance of class B. Should i create B instance inside A constructor, or create instance where class A is initiated and pass instance to A constructor?

计划A:

class A { constructor() { this.b = new B(); } }

计划B:

const b = new B();

class A() { 
    constructor(b) { 
        this.b = b; 
    }
}

const a = new A(b);

推荐答案

如果

  • 将来不应将B类替换为C类

  • Class B should not be replaced with class C in a future

Class B不使用某些外部依赖项,例如ajax或数据库或其他东西.

Class B not using some external dependency like ajax or database or something else.

OR

  • 您的应用程序是概念证明,或者您确实有时间限制

计划B在所有其他情况下都很好.

它将为您带来快速更改A类行为的灵活性,赋予更多通用性,并通过模拟此依赖项来帮助进行测试.

It will bring you flexibility to change your A class behavior on the fly, grants more universality, helps with testing by mocking this dependency.

所以我要说计划A与简单有关,计划B与灵活性和测试有关.在每种情况下选择所需的任何内容

So I would say that plan A is about simplicity, plan B is about flexibility and testing. Choose whatever you need in every current case

希望这会有所帮助.

这篇关于ES6类和类实例作为构造函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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