What are static methods and how should they be used? Watch this video to find out!
When declaring a method on a class we have two options instance or static. 0:00 In this video I'll show you what a static method is and how they can be useful. 0:05 And if you'd like to follow along open the workspace for this video. 0:09 A static method is one that exist on the class decoration and 0:12 is not accessible through an instance. 0:17 You can only call the function by referencing it's class. 0:19 In the file static.js I have a bird class with a static method 0:22 called change color and by default the color is set to red. 0:26 Now the interpreter knows this is a static function 0:31 because the line starts with the static keyword. 0:34 So let's see how this works. 0:37 First, I'll create a new bird, I'll call it redBird, 0:39 since that's the default color. 0:43 Then I'll log the initial value of redBird's 0:50 color by saying console.log redbird.color. 0:54 Next, I'll call change color on redBird, 1:01 by typing redBird.changecolor, and 1:06 I'll set the color to blue. 1:11 And finally, I'll log the current value of redBird's color, 1:14 with console.log redBird.color. 1:20 So, let's see what happens. 1:28 Over in the console, I'll run node static.js and 1:30 it looks like I get an error. 1:35 It says red bird that change color is not a function well since 1:37 change color is a static method I can't access it through my redBird instance. 1:43 Now we can do a couple of things to fix this the quickest solution is to call 1:49 change color with our instance as the context. 1:53 So over in the changed color call we can say 1:57 Bird.changeColor.call then pass redBird, then blue. 2:02 So here the static method takes the instance of redBird and 2:10 applies the color change. 2:15 So over in the console we can see that the color changes from red to blue. 2:17 The other thing we can do is rewrite the static method 2:23 to take an instance as a parameter. 2:26 So over in the static method we'll pass the parameter bird and 2:29 then instead of this.color will change it to bird.color. 2:34 By passing the instance to the method we avoid confusion 2:40 of how the method is to be used. 2:44 So now I can call change color without using the call method, right? 2:46 So over in the consul if I run node static.js, perfect. 2:53 Great job following along. 2:59 In the next video we'll look at using getter and setter methods in a class. 3:00
You need to sign up for Treehouse in order to download course files.Sign up