JavaScript Classes - Object Oriented Programming

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Classes - Object Oriented Programming

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basic

class Car {
constructor(name) {
this.name = name;
}
drive() {
console.log(this.name, 'driving');
}
}

const toyota = new Car('toyota');
toyota.drive(); // toyota driving

const subaru = new Car('subaru');
subaru.drive(); // subaru driving

Property Initializer

class Counter {
count = 0;
increment() {
this.count++;
}
}

const counter = new Counter();
console.log(counter.count); // 0

counter.increment();
console.log(counter.count); // 1

Private Properties

class Event {
#eventName;
constructor(eventName) {
this.#eventName = eventName;
}
fire() {
console.log(this.#eventName);
}
}

const evt = new Event('click');
evt.fire(); // click

evt.#eventName = 'open'; // ERROR: Private field

Static Members

class Square {
static howManySquares = 0;
constructor(size) {
Square.howManySquares++;
this.size = size;
}
area() {
return this.size * this.size;
}
}

const unit = new Square(1);
const quad = new Square(4);

console.log(Square.howManySquares); // 2

Getters and Setters

class RangedValue {
#current;
constructor({ min, max, value }) {
this.min = min;
this.max = max;
this.#current = value;
}
get value() {
return this.#current;
}
set value(newValue) {
this.#current = Math.max(this.min, Math.min(this.max, newValue));
}
}

const ranged = new RangedValue({ value: 5, min: 0, max: 10 });
console.log(ranged.value); // 5

ranged.value = 15;
console.log(ranged.value); // 10

Inheritance

class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log('yum yum');
}
}

const simple = new Animal('Dimple');
console.log(simple.name); // Dimple
simple.eat(); // yum yum

class Bird extends Animal {
constructor(name, weight) {
super(name);
this.weight = weight;
}
fly() {
console.log(this.weight > 3 ? 'Too fat to fly' : '🎤 I believe I can fly 🎤');
}
}

const bird = new Bird('Polly', 2);

console.log(bird.name); // Polly
bird.eat(); // yum yum

console.log(bird.weight); // 2
bird.fly(); // 🎤 I believe I can fly 🎤

instanceof

class Alpha { }
class Beta { }

const alpha = new Alpha();
const beta = new Beta();

console.log(typeof alpha); // 'object'
console.log(typeof beta); // 'object'

console.log(alpha instanceof Alpha); // true
console.log(alpha instanceof Beta); // false

console.log(beta instanceof Alpha); // false
console.log(beta instanceof Beta); // true
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

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.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36