问题
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