What is the recommended way to access the instance of a class and its methods from, say a DOM button? Consider this example: Right now I am calling a static method of an ES6 class, because I don't know how to call the instance method:
<script src="MyClass.js">
<button onClick="MyClass.buttonClicked()">
The class looks like
class MyClass() {
static instance;
constructor() {
instance = this;
//important initialization of some vars
}
static buttonClicked() {
MyClass.instance.nonStaticButtonClicked();
}
nonStaticButtonClicked() {
console.log("button clicked!");
//use the vars which have been initialized in constructor()
}
}
This works flawless in Chrome and not at all in Safari, because apparently Safari doesn't like the static variable declaration and gives the error "Unexpected token '='. Expected a ')' or a ',' after a parameter declaration.', see also the comment of Marthinus Engelbrecht here: SyntaxError: Unexpected token '='. Expected a ')' or a ',' after a parameter declaration.' in safari
My question is, if what I do is wrong, how should I do it right? In particular, what is the best approach to access an instance method from a button?
EDIT: I was just overcomplicating things:
window.addEventListener("load", function() {
window.myClass = new MyClass();
});
and the button:
<button onClick="window.myClass.nonStaticButtonClicked()">
No need for static calls and instances/singletons. Thanks everyone.