Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Assign and Access Methods of a JavaScript Class with Static Properties

    Tyler ClarkTyler Clark
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss