将Javascript类(ES6)拆分为多个文件? [英] Split a Javascript class (ES6) over multiple files?

查看:758
本文介绍了将Javascript类(ES6)拆分为多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript类(在ES6中)已经很长了.为了更好地组织它,我想将其拆分为2个或3个不同的文件.我该怎么办?

I have a Javascript class (in ES6) that is getting quite long. To organize it better I'd like to split it over 2 or 3 different files. How can I do that?

当前在单个文件中看起来像这样:

Currently it looks like this in a single file:

class foo extends bar {
   constructor(a, b) {} // Put in file 1
   methodA(a, b) {} // Put in file 1
   methodB(a, b) {} // Put in file 2
   methodC(a, b) {} // Put in file 2
}

谢谢!

推荐答案

创建课程时

class Foo extends Bar {
  constructor(a, b) {
  }
}

您稍后可以通过分配给其原型为该类添加方法

you can later add methods to this class by assigning to its prototype:

// methodA(a, b) in class Foo
Foo.prototype.methodA = function(a, b) {
  // do whatever...
}

您还可以通过直接分配给类来类似地添加静态方法:

You can also add static methods similarly by assigning directly to the class:

// static staticMethod(a, b) in class Foo
Foo.staticMethod = function(a, b) {
  // do whatever...
}

您可以将这些函数放在不同的文件中,只要它们在声明类后后运行.

You can put these functions in different files, as long as they run after the class has been declared.

但是,构造函数必须始终始终是类声明的一部分(您不能将其移动到另一个文件中).另外,您需要确保定义了类方法的文件在使用之前已经运行.

However, the constructor must always be part of the class declaration (you cannot move that to another file). Also, you need to make sure that the files where the class methods are defined are run before they are used.

这篇关于将Javascript类(ES6)拆分为多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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