Assign and Access Methods of a JavaScript Class with Static Properties

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

When used, the static keyword assigns properties and methods to the class itself. As opposed to assigning it to the prototype object of that class. We'll use the static keyword and show how to replicate the same behavior with a regular function.

Instructor: [00:00] If we had a class called Food and it had a method called isHealthy that returned true and we console.log Food.isHealthy, we'll get an error. This is because isHealthy doesn't actually live on the class but is actually written to the prototype object of our class Food.

[00:19] In order for us to call this, we'll have to add the static keyword. By adding the static keyword, it's going to take this property and assign it to the class instead of assigning it to the prototype of the class.

[00:31] This would be the same as creating a function called food and then assigning it a property called isHealthy that is a function that returns true. Now a console.log stays true.

[00:46] If we go back to our class Food by removing this function and un-commenting out our code...Now if we did static canBeEaten and it returns Food.isHealthy...Now we update our console.log to canBeEaten.

[01:01] We see that we get a return value of true. Static properties can be called within its own class. We can also refactor this to use the this keyword, which will work all the same because the this keyword is referencing the Food class.

alwin
alwin
~ 6 years ago

Just the same with Java.

Markdown supported.
Become a member to join the discussionEnroll Today