01 / 04
Not only data but doing
The classes so far only settled "what values it holds".
But a real one has things it can do as well. A robot can greet you; an order can work out its amount. Those "things it can do" go on the blueprint too.
One blueprint, many objects
INPUT · Slides
01 / 04
The classes so far only settled "what values it holds".
But a real one has things it can do as well. A robot can greet you; an order can work out its amount. Those "things it can do" go on the blueprint too.
02 / 04
Write name() { } inside a class's { }. This is called a method — a function the class owns.
You do not write function. To call it you write instance.methodName(), with a ( ) on the end.
class Robot { hello() { console.log("beep boop"); }}const r = new Robot();r.hello();Result
beep boop
03 / 04
A method is one of the function family, so it can catch parameters and send values back with return.
What comes back is an ordinary value. You can show it or use it in a sum as it stands.
class Machine { double(n) { return n * 2; }}const m = new Machine();console.log(m.double(7));Result
14
04 / 04
The constructor and the methods sit side by side in the same { }. No , between them (that is where it differs from an object literal).
Write as many methods as you like. Think of it as the place where you line up "the things anything made from this blueprint can do". Off you go.
class Robot { constructor(name) { this.name = name; } greet() { console.log("beep boop"); }}const r = new Robot("Clank");console.log(r.name);r.greet();Result
Clank beep boop