是否可以在ES2015中导入类方法 [英] Is it possible to import class methods in ES2015

查看:99
本文介绍了是否可以在ES2015中导入类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个模块中创建一个方法:

 导出函数myMethod(){} 

在另一个模块中实例化一个类:

 code> import {myMethod} from'./methodFile'; 
class MyClass {
constructor(){}
myMethod //不工作
}

是否可以使用 myClass 类的一部分 myMethod



我尝试创建相当于以下代码的代码:

  class MyClass {
constructor(){}
myMethod(){}
}


解决方案

不,不可能引用 class 声明中的给定值。



但是, class 语法主要是语法糖,并且原型继承总是起作用。你可以简单地把方法放在类定义之后的原型对象上:

  import {myMethod} from'./methodFile'; 
class MyClass {
...
}
MyClass.prototype.myMethod = myMethod;

如果您的方法需要使用 super 您需要使用 .toMethod 方法。 p>

I'm creating a method in one module:

export function myMethod() {}

And instantiating a class in another module:

import {myMethod} from './methodFile';
class MyClass {
    constructor() {}
    myMethod // doesn't work
}

Is it possible to use myMethod as part of the MyClass class?

I'm trying to create the equivalent of the following code:

class MyClass {
    constructor() {}
    myMethod() {}
}

解决方案

No, it is impossible to reference given values in class declarations.

However, class syntax is mostly syntactic sugar, and prototype inheritance works as always. You can simply put the method on the prototype object after the class definition:

import {myMethod} from './methodFile';
class MyClass {
    …
}
MyClass.prototype.myMethod = myMethod;

If your method needs to use super, you'll want to use the .toMethod method.

这篇关于是否可以在ES2015中导入类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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