Reputation: 11424
I have a class defined as follows:
export default class MyClass {
myMethod(code){
console.log("The code is" + code)
}
}
How can I access it from my main class? In the main class I have the following lines of code:
import MC from './MyClass'
...
MC.myMethod("987");
The error I am getting is:
undefined is not a function (evaluating '_MyClass2.default.myMethod("987")'
What am I doing wrong? Also, what do the _
, 2
, and default
mean in the error message next to my class name?
Upvotes: 1
Views: 54
Reputation: 2032
When declaring a JS Es6 class, remember that its method members are bound to each instance of the class or bound to the class itself if you used the static keyword :
class MyClass {
myMethod() {
// each object created with the *new* keyword will have this method:
// const o = new MyClass();
// typeof o.myMethod === "function" will return true
}
}
class MyClass {
static myMethod() {
// typeof MyClass.myMethod === "function" will return true
}
}
Depending of its declaration, when invoked its lexical context this will either be bound to the instance (first case) or the class itself (2nd form).
You should also now that all instance methods (like the second case) are put inside the prototype property of you class. So you have :
class MyClass () {
myMethod() {}
}
(typeof MyClass.protototype.myMethod === "function") // true
const o = new MyClass()
(o.myMethod === MyClass.prototype.myMethod); // true
For static methods (or class methods) the method is directly attached to the class object.
The error you see in your case is caused because your method was not declared with the static keyword.
Upvotes: 1
Reputation: 211700
That's because you've created an instance method, so you have two options. Either create an instance of that class:
var c = new MyClass();
c.myMethod();
Or set that as a static
method:
static myMethod(code) {
// ...
}
Another way is to export
the functions directly:
export myMethod(code) {
// ...
end
Upvotes: 2
Reputation: 3867
You need to declare an object of your class before start calling its methods just like in any other programming languages.
export class MyClass {
public myMethod(code){
console.log("The code is" + code)
}
}
Then import it wherever you want to use
import MC from './MyClass'
Create an object from your import and call the method
var mc = new MC();
mc.myMethod("987");
Upvotes: 0