Read the statement by Michael Teeuw here.
What is the difference between these function definitions?
-
I keep on seeing people adding their own functions in their
MMM-Module.js
.
Some people write:updateDomIfNeeded: function() { ... }
while others prefer to just write:
myfunction() { ... }
What is the difference to MM, if any?
-
@E3V3A The former is object notation; therefore, you need to be defining an object. For example:
var Lemon = { skinColor: "yellow", juice: 10, // in mL squeeze: function() { return this.juice; } }
That way, for each
Lemon
you can callLemon.squeeze()
. It is relative to itself; the Lemon returns itsjuice
, that it only knows about because it’s a complete object.Meanwhile, if you have
myFunction()
it doesn’t belong to an object. It just exists. You can call it from anywhere asmyFunction()
. You can even assign it to another variable and call it from there (this is also why you can pass a callback function as an argument):var myFunction = new function(){ ... } var otherFunction = myFunction; otherFunction();
You can also have “lambda” functions that have no name.
But, to answer your question, you can only use the “object” style if you’re in the middle of defining an object. An “object” style function (most often called a “method” of the object) can also reference the object itself, whereas as a function without an object needs it to be passed as a parameter, such as
squeeze(someLemon)
. -
@ninjabreadman Fantastic! Again, the best explanation I’ve heard! I love that juice analogy!
Thank you so much for having patience with all my dumb questions. Surely a lot of them are trivial to most developers. (If you’re a moderator, feel free to mark this as solved.)