If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Modern JavaScript has excellent support for classes and you can think of a JavaScript plus as the reusable blueprint for creating objects. We can create a car object called Toyota that has a name property pointing to the string Toyota and a drive function that logs toyota.name along with the string driving and we might have other car objects in our code base as well. For example, Subaru that follows a similar structure of course with the name being different and the different name being used in the drive function. Now wouldnt it be great if he could create a reusable blueprint for creating such objects? And that is exactly where JT strip classes come in.
00:34
We define a class using the class keyword and provided a name called car in this particular case. And you can use any valid towers kept identifier. It is conventional to use Pascal casing for this. So that is why we have made the C of car capital when we create an instance of the class if provided a special function called constructor is what will execute. Constructors are defined using the constructor keyword and they have access to the instance of the object that has been created by using the special this keyboard.
01:05
So here in our constructive function we accept a name property and initialize a property name on the object that we are creating. Using that provided value, we can define the methods that we would want on our object as well. For example, here we just want a simple drive method. Within our methods we can access the instance of the object that we are dealing with by using the this keyboard, just like we did in the constructor to create an instance of the class, you invoke the class very similar to how you would invoke the function except that you must prefix with the new keyword. So this new car call will invoke that constructor.
01:39
We are passing in Toyota and that will set this.name to Toyota, which means that now when we invoke the drive method on this created object, of course we are going to see that name along with the string driving. Now that we have this blueprint, we can create as many instance objects as we want. For example, we can easily create Subaru bypass passing in Subaru. And now when we drive the Subaru, we see Subaru driving JavaScript classes allow you to provide a default value for any member by using the property initializer. For example, consider a simple counter where we have a account member, which we want to start from zero.
02:12
We can declare that by providing an identifier for that member, followed by the equal sign, followed by the initial value that we want. Now all instances of this counter will automatically get this count property with the value initialized to zero. And we can use that just like any other property on the object. For example, within an increment method, we can access it using this and increment the value of count by one. Let's demo these facts very quickly by creating an instance of the counter and you can see that the initial value of count from that counter variable is going to be zero. And of course after we invoke the counter dot increment method,
02:47
the counter dot count increments to one modern JavaScript allows us to have private properties on a class, which helps us ensure controlled access to its members. Consider a simple event class and within its constructor we Take an event name string and we initialize the event name property based on that value. We have a simple method called fire, which is going to log out the fact that that particular event has occurred. As an example, we create a simple event object that is designed to only fire clicks and of course event dot file logs the message click. Now by default, all properties on this object are public,
03:20
which means that we can actually just use event, event name to modify that to be open. And now this event will start firing open and we want to prevent this kind of behavior. We want this object to only file click events. So let's create a better version of this event class and this time use a private property for the event name. Now all private properties on a class must be declared upfront. So here we are declaring the private property event name and the way JavaScript identifies a property as private is that we must prefix it with the hash character and then we can create the remaining class body very similar to how we
03:55
had it before. The key difference is that every single time we previously had this event name, now we have this hash event name because that is the name of our private property In terms of usage, of course we can create an event instance passing the string click and event or file will log out click. The key feature of a private field is that we cannot access it outside of the class body. So if we try to access hash event name off of the event object, this is going to result in an error because the private field can only be accessed within the containing class. Of course, if you remove this invalid access of event name,
04:30
the code will function perfectly fine as you would expect, just like other modern programming languages, JavaScript classes also support static members and these are attached to the class and not the instance and therefore they can be shared across all the instances. Consider a simple class called square and we have a constructed that takes a size and initializes the size property and a method that returns the area based on the value of the size. We can create instances of the square quite easily. For example, a unit square where each side is one and a quad square where each side is four. Now imagine we are trying to do some performance optimization on our application
05:05
and we want to keep track of how many squares we are creating. We could create a global variable, but that might leak all over our code base. Fortunately, we can actually declare a static member on the square class. Here we are saying that the square class has a member called how many squares, which we are initializing to zero. And every single time we create a new instance, of course the construc will get called and we can take this as an opportunity to increment square. How many squares by one a static properties belong on the class and not on the instance you access them using the class name.
05:40
So in this example we are doing square dot and we use the same syntax for accessing this static property anywhere within our code base. So as an example, after we've created the two squares, we can access squared at how many squares and of course the answer should be two. We know that JavaScript Objects allow you to define getters and sitters which look like functions when you define them, but behave like simple values when you use them. And you can define getters and sitters in your class as well. And of course the main objective is controlled, yet convenient access to the underlying values. Consider this simple class called ranged value and our objective is to take a
06:17
minimum, a maximum and a value and to make sure that when a new value is provided, it stays within the range min and max. We back that value up with a private field called current and this makes sure that this doesn't leak out of our class. So now within our constructive, we accept a simple object that has the members min max and value, which we destructure into simple local variables. We initialize the members Minto min max to max and current to value. We define a getter for the value member by using the get keyword followed by a function definition which simply returns the value from this dot current private
06:52
property. Similarly, we can define a setter with the set keyword followed by a function definition that accepts a new value. And of course we will use this value, clamp it between the range min and max and then assign it to the current private property. Now getters and setters are declared like they are functions, but all usage of them is pretty much like standard properties. So we can create a new instance of the range value and then we want to read the current value. We use simply range value. We do not need any brackets like you would with a function call. And similarly writing to the value is done using the assignment operator.
07:27
So if you try to assign a range value to 15, which is outside our range, zero to 10 our setter will get invoked and it'll cramp it to the max value, which is 10. A key tenant of object oriented programming is class inheritance, which is one of the ways in which you can create classes that reuse some base features and then extend that with additional utilities. Let's consider the classic example inspired by the animal kingdom. We have a base class called animal that takes a name value in its constructed and assigns it to the name property and then provides a utility method called eat that simply logs. Yum, yum.
08:02
So of course we can create a simple animal instance called a dimple. Read the name dimple and eat a yum yum way. A bird is just an animal which means that it has all the features of the animal. And to declare this fact when we create the class bird, we use the extens keyword to extend animal within our constructor. In addition to the name perimeter, which is required by animal, we take an additional one called weight. Before we do any of the bird initialization, we want to make sure that any initialization code that exists within the constructor of animal executes and we can do that with a function called using the super keyword. This will invoke the animal constructor,
08:37
allowing it to set up the name and we can continue by setting up the weight property ourselves. We can add additional methods to the bird as well. For example, we can add a fly method and in this particular case we will make sure that the weight is not greater than three. And if it is, then the bird is too fat to fly, otherwise it believes It can fly. Now since the bird extends the features of animal, when we create a new instance of the bird, it has access to the name property, it has access to the eat function. Yum, yum. But of course it has its own features as well. So if we log out the bird, wait, since we passed in two for poly, that is what we get. And similarly,
09:13
when we invoke bird fly, Polly believes that she can fly. JavaScript comes with a built-in operator called instance off that can be used to determine if a particular object is an instance of a particular class. To demonstrate the usage of the instance of operator consider two very simple classes. In fact, they are so simple that they, they're completely empty and they will create empty objects. As far as visibility is concerned, we create simple variables and instance of the alpha and the instance of the beta. Now the type of operator on all instances of classes actually gives back the literal string object because after all classes are blueprints for creating
09:49
objects. Despite this, JavaScript is smart enough that you can use the instance of operator to determine if a particular object was created from a particular class since the variable alpha was created from the class alpha variable alpha instance of class alpha returns. True and alpha instance of beta returns false. Similarly for the beta variable beta instance of alpha will return false and beta instance of beta will return true fun fact JavaScript was around for quite a while before it got the special syntax for class definitions that we have covered in this tutorial and there is note knowing that it has made it a much
10:24
more accessible language. As always, thank you for joining me and I will see you in the next one.