Don't worry about formatting, just type in the text and we'll take care of making sense of it. We will auto-convert links, and if you put asterisks around words we will make them bold.
Tips:
For a full reference visit the Markdown syntax.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
I'm just posting this up here because I had a bunch of questions in a PM and it seems what's needed is a very clear explanation about how classes work in JS.
Hopefully this will be useful:
ES6 Classes aren't magic - they're just a neat way of writing JavaScript functions
Methods
Static Methods
Using them
You can't access a method like you'd access a static method, and you can't access a static method like you'd access a method. They're different and are accessed in different ways.
Using
this
this
isn't magic either. Looking at this code:If you use
.
to call a function (eg.color.sayhi()
) thenthis
is set to the bit before the.
, egcolor
, whensayhi()
is called.Similarly, if you make a static function, it won't have access to the class instance via
this
because in order to call the static function, you're not callingcolor.function()
butColor.function()
- andColor
is the class, butcolor
is the class instance.If you call another function - especially with
setTimeout/setInterval
this
can get reset:There are a bunch of ways to work around it:
Using modules and classes
Right now, The Espruino IDE's minification doesn't handle classes well (it just turns them back into ES5 functions). However you can always set it just for whitespace.
But: neither modules nor the
exports
variable is remotely magicWhen you use
require("mymodule")
, all Espruino does is run your module code, and then replacerequire("mymodule")
with whatever was in theexports
variable after the module finished runningSo if you do this:
Then just like if you did this to any other variable,
require("mymodule")
will be equal to"The actual thing"
, not any of the stuff it was set to before.Exporting a class
It's super-easy, just do:
This is identical to just having it all in one file, without the lines
exports = Color;
andvar Color = require("mymodule");