How to import a static member of a class?

自闭症网瘾萝莉.ら 提交于 2021-02-04 19:49:14

问题


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

Destructuring works on the static method of a class:

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

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

However, I thought imports behaved like destructuring assignments. If that's true, then I would expect the following to work. But, when I attempt to import the walk method, it just comes back as undefined:

Destructuring through imports, why doesn't it work?


person.js

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

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?


回答1:


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;

This means that the import brackets are not the same as a destructor assignment.

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;



回答2:


The syntax you are using is actually a named import, not a destructuring assignment, although they look similar. There is no destructuring import in ES6. All you can do is to add a destructuring assignment to the next line, but keep in mind that this will break when the imports are cyclic.

import Person from './person';
const { walk } = Person;
console.log(walk);


来源:https://stackoverflow.com/questions/45639934/how-to-import-a-static-member-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!