如何导入类的静态成员? [英] How to import a static member of a class?

查看:59
本文介绍了如何导入类的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用标准导入语法将类的静态成员导入文件.给出上下文:

I am trying to import a static member of a class into a file by just using standard import syntax. To give context:

class Person {
    static walk() {
        console.log('Walking');
    }
}

let {walk} = Person;
console.log(walk); // walk function


但是,我认为导入的行为就像是销毁分配.如果是这样,那么我希望以下内容能奏效.但是,当我尝试导入walk方法时,它只是返回为 undefined :

person.js

person.js

export default class Person {
    static walk() {
        console.log('Walking');
    }
}


walker.js


walker.js

import {walk} from './person';
console.log(walk); // undefined


由于这似乎不起作用,如何将静态方法从一个类导入另一个模块?


Since this doesn't seem to work, how can I import a static method from a class to another module?

推荐答案

export default can be mixed with normal exports in ES6. For example :

// module-a.js
export default a = 1;
export const b = 2;

// module-b.js
import a, { b } from "./module-a";
a === 1;
b === 2;

这意味着导入括号与析构函数分配.

ES6规范实际上无法实现您想要实现的目标.最好的方法是在导入后使用解构

What you want to achieve is actually not possible in the ES6 specs. Best way to do it, would be to use the destructuring after your import

import Person from "./person";
const { walk } = Person;

这篇关于如何导入类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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