I’ve been around javascript for a long time, but am pretty rusty with javascript Classes. For a particular project I’m working on, things are starting to get unwieldy and I’d like to start cutting up my code into separate files. I don’t want to have to import
all my functions explicitly, so I’ve started wrapping them up into a Class
(which makes sense for other reasons also). Some of my functions return callbacks (functions). That is:
return functionName;
Which I can use like:
var callBack = functionReturningFunction();
...
callBack();
I cannot find any information about returning and passing methods, rather than functions what is the syntax there? Ideally I’d like to pass in methods as arguments to the constructor so I can say:
const myObject = new MyClass(methodName);
So I don’t have to do:
const myObject = new MyClass();
myObject.methodName();
2
Answers
The stackoverflow fairy brought me the answer as I was finishing typing out the question. Following the pattern in my question, I have:
Which I can use like:
From outside my Class. Importantly I should have:
inside
methodReturningMethod()
ifaMethod()
accesses any object properties because javascript is * special * like that (and will get all confused if I don't).Inside class methods I can have stuff like:
which will call whichever method
this.methodReturningMethod()
returns.I don't think its possible to specify an object method as a parameter to that object's constructor because object methods don't exist before the object has been constructed. Shout out if you know a way. After the object has been created I can do things like:
Just basic common info for your:
You don’t need class to provide them in NamesSpaces
You can create file helper.js:
and then basicly include them from:
and then …
Good Luck with your project! 😉