Javascript - Methods in Classes
Code Life
By Pierre Marsaa
Behaviour Shared by Every Object
Imagine every Codémon needs an attack() action. If you write that function inside each object literal, every Codémon carries its own copy of the exact same code — and fixing a bug means fixing it in every single object:
↗️
Loading editor...
↶
↷
In a class, a method is written once, right after the constructor, using the same short syntax as in an object literal. Every object built from the class can then call it:
↗️
Loading editor...
↶
↷
One attack() for the whole class: change it in one place and every Codémon instantly gets the new behaviour. Inside the method, this.name reads the name of whichever Codémon called it — zap or aquachu.
Verify