YTread Logo
YTread Logo

Object-oriented Programming in JavaScript: Made Super Simple | Mosh

Jun 07, 2021
So what is

object

-

oriented

programming

? Object-

oriented

programming

is a programming paradigm or programming style that focuses on

object

s instead of functions. It's nothing new, it's been around since the 70's, but unlike tools and frameworks that come and go. It is still very relevant today because it is not a programming language or a tool, it is a programming style or a programming paradigm. There are several programming languages ​​that support object-oriented programming, such as c-sharp Java Ruby Python JavaScript and more now JavaScript. It's a bit controversial, but I'll get to that later. You might be interested to know that many of the popular frameworks you might be using are actually designed with object-oriented programming concepts in mind.
object oriented programming in javascript made super simple mosh
Angular is an example of these frameworks. So object-oriented programming is a very popular programming style and comes up in many technical interviews, so if you really want to be a serious developer, you need to understand object-oriented programming as a technical interviewer if I see a candidate with objects. object-oriented programming on the resume that candidate stands out for me and that is where this intensive course comes in in this course you will learn and understand object-oriented principles and how to implement them in JavaScript my name is Mohamad ani and I am I will be your instructor in this course.
object oriented programming in javascript made super simple mosh

More Interesting Facts About,

object oriented programming in javascript made super simple mosh...

If you enjoyed this video, please like and share it with others and be sure to subscribe to my channel for new videos every week. You can also follow me on Twitter as Masch a Madani, so now let's get started. The popular interview question concerns the four core concepts in object-oriented programming. These concepts are encapsulation, abstraction, inheritance and polymorphism. Let's look at each of these concepts. Before object oriented programming we had a programming procedure that divided a program into a set of functions, so we have data stored in a bunch of variables and functions that operate on the data, this style of programming is very

simple

and Straightforward, it's often what you learn as part of your first programming course at a university, but as your programs grow, you'll end up with a bunch of functions all over the place, you might find yourself copying and pasting lines. of code over and over again, you make a change in one function and then several other functions break, that is what we call spaghetti code, there is so much interdependence between all these functions it becomes problematic object oriented programming came to solve this problem in in object-oriented programming we combine a group of variables and related functions into a unit we call that unit an object, we refer to these variables as properties and functions as methods here is an example Think of a car, a car is an object with properties like make, model, and color and methods like start, stop, and move.
object oriented programming in javascript made super simple mosh
Now you might say wow, we don't have cars in our programs, give me a real programming example. Well, think about the venue. Storage Object In each browser your browser has a local storage object that allows you to store data locally. This local storage object has a property like length which returns the number of objects in the storage and metals like set element and delete element, so it is object-oriented. In programming we group related variables and functions that operate on them into objects and this is what we call encapsulation. Let me show you an example of this in action.
object oriented programming in javascript made super simple mosh
Here we have three variables: base salary over time and rate below these, we have a function to calculate. the salary of an employee we refer to this type of implementation as procedural, so we have variables on one side and functions on the other side, they are strongly decoupled. Now let's look at the object-oriented way to solve this problem we may have. an employee object with three properties: a time and rate based salary and a method called getsalarynow, why is it better? First of all, look at the salary earning function. This function has no parameters. In contrast, in an example procedure, our salary getter function has three. parameters the reason why in this implementation we don't have any parameters is because all these parameters are actually modeled as properties of this object, all these properties and get the salary function are highly related, so they are part of one unit, so one of the symptoms of procedural code is functions with so many parameters, when you write code in an object oriented way your functions end up having fewer and fewer parameters, like Uncle Bob says, the best functions are those that don't have parameters, yes the smaller the number of parameters the easier it will be to use and maintain that function, so that is encapsulation, now let's look at abstraction, think of a DVD player as an object, this DVD player has a complex logic board inside and some buttons on the outside that you interact with, just press the play button and you don't care what happens inside, all that complexity is hidden from you, this is abstraction, in practice we can use the same technique in our objects to be able to hide some of the properties and methods from the outside and this gives us a couple of The first benefit is that we will simplify the interface of those objects by understanding that an object with some properties and methods is easier than a object with various properties and methods.
The second benefit is that it helps us reduce the impact of the change. Imagine that tomorrow we change these internal or private methods, none of these changes will leak to the outside because we don't have any code that touches these methods outside of their content object. We can delete a method or change its parameters, but none of these changes. It will affect the rest of the application code, so with abstraction we reduce the impact of the change. Now for the third core concept in object-oriented programming inheritance. Inheritance is a mechanism that allows you to eliminate redundant code.
Here's an example: Think of HTML elements as text boxes. dropdown lists, checkboxes, etc., all these elements have some things in common: they should have properties like hidden and internal HTML and issues like click and focus instead of redefining all these properties and methods for each type of HTML element, we can define them. once in a generic object, call it HTML element and have other objects inherit these properties and methods, so inheritance helps us eliminate redundant code and finally, poly polymorphism means many transformations means shape, so the polymorphism means many ways in object-oriented programming polymorphism is a technique that allows You to get rid of long ethanol or switch and case statements, so let's go back to our example of HTML elements, all of these objects must have the ability to be represented in one page, but the way each element is rendered is different from the others if we want to render multiple.
HTML elements procedurally, our code would probably look like this, but with object-oriented we can implement a render method on each of these objects and the render method will behave differently depending on the type of object the object is referencing. viewer so we can get rid of them. this nasty shift and capital and use a line of code like this you will see that later in the course here are the benefits of object oriented programming using encapsulation we group related variables and functions together and this way we can reduce the complexity now we can reuse these objects in different parts of a program or in different programs with abstraction we hide the details and the complex and show only the essential this technique reduces the complexity and also isolates the impact of changes in the code with inheritance we can eliminate redundant code and with polymorphism We can refactor ugly change case statements to follow this course.
All you need is a code editor and a

simple

web server. The editor I will use here is Visual Studio Code or vs code which you can download from Visual Studio Code. but feel free to use any editor now with vs code. We have this extensions panel here. Search for live server. This is a very simple and lightweight server that we will use to serve our application, so install it and then here in the files panel. let's add a new file index with dot HTML now to generate a basic HTML template. We can simply type an exclamation point and press tab to get a very basic HTML template.
Now let's add a script element so that the script with the source code is set to the J s index. write all of our JavaScript code inside this file, so let's add a new file and save it as J s index and finally, to make sure we've set everything up correctly, let's make a console that logs hello world now when you install the live server. You should see this menu here in the status bar if you don't see you probably have to restart vs code and if you still don't see it just right click on index.html and select open with live server so it will fire up chrome pointing to this address now let's open the chrome development tools here in the console tab we have hello world so before we continue I want to emphasize that this course is not for beginners it is for intermediate level developers so you should keep in mind At least three months of experience programming in JavaScript.
You must know the basics. You should know how to use Chrome's development tools. I will not cover them in this course. Our approach is purely object-oriented programming with JavaScript. JavaScript is a number of objects, so in order. To learn object-oriented programming, you must first have a good understanding of objects, so in this section I will cover some fundamental concepts about objects, such as creating object factories and primitive constructors and reference types on how they behave. different way when working with properties. of an object, such as adding, removing properties, and enumerating them, you will also learn how to define private properties, as well as getters and setters.
If you know all these topics well, feel free to skip this section and move on to the next section where I talk about prototypes, otherwise continue watching, so now let's start, let's start this section by creating an object, so I will use the keyword let in es6, it is the replacement for var, so in es5 and before we had var to declare variables, but para has a number of problems when it comes to scope that are beyond the scope of this course. I just want to let you know that as a best practice, stop using var and use let or Const with cons, you are basically defining a constant, so you will win.
I won't be able to reassign it if you want to reassign a variable. Now in this demo I'm going to use Const to define a constant, so let's call this circle and set it to an object. Here I'm using object literal syntax for these curly braces, we refer to them as object literal syntax, an object in JavaScript is essentially a collection of key-value pairs, so inside these curly braces I'm going to add some key-value pairs. value let's add radius and set it to 1 let's add another key as location now this time the value can be an object so again I am using object literal syntax on this object we can have a couple of key-value pairs like x and y now let's add another key-value pair so that the keys draw the value as a function. that's for drawing the circle, so for now let's do a simple console.log.
Now I want to define some terms here. This circular object has a radius location of three members and draw if a member is a function, we refer to that as a method. here we say that draw is a method, these other members are what we call properties now in some JavaScript tutorials they refer to all these members as properties whether there are functions or not, but technically in object oriented programming properties and methods They are fundamentally different because a property is used to hold values, a function or method is used to define some logic, so now that we have this circular object we can access its members using dot notation, so look at the circular dots here are the members that we can call the draw method.
Now look here. on the right side I have chrome open, these are the chrome developer tools. As soon as I save my changes here you will see that Chrome will be updated because here with live server we have hot reloads so save and here is the result as soon as we change our code the new code is loaded inside Chrome so so the object literal is a simple way to define an object, but we can also define objects usingfactories and builders and that is the topic of the next conference. Now let's imagine that we want to create another one. circle with the current implementation we have to duplicate all this code in this way now this can be a problem if we have one or more methods on our object in this case we have this draw method here and as you can see we have duplicated it in two different places, so if there is a bug in this method, we have to go back and fix it in multiple places.
Now this is a very simple object. Imagine if the circular object had ten methods, so object literal syntax is not a good way to create an object. and duplicate it if this object has at least one method, if an object has one or more methods we say that that object has a behavior like a person who can do different things then it has a behavior. Now let's imagine that we don't have this duplicate drawing method. this object wouldn't be a big deal so basically we would end up with two objects and then here we could use different values ​​so creating objects with object literal syntax is a problem only if that object has behavior so what is the solution ? use a factory or constructor function, so let me show you how it works.
I'm going to delete this second circle and define a function called create circle. Now I'm going to move all of this code inside this new function, like this. Now there is no need to declare a constant, we can simply return this object. Now this circle requires a radius, so instead of hardcoding one here, I'll add a parameter here, radius and then set it here, now in es6, we have this new feature. If the key and value are the same, we can eliminate the noise in the code by removing the value so we can just add radius.
Now, to simplify the code so you can focus on what I'm going to teach you, I'll remove this location property, we really don't need it. Instead, I'll add our draw method, key value and let's make a simple console. nut lock draw okay this is what we call a factory function now we can simply call this function to create a new circle so we call a constant circle create circle and pass one as radius now there is another way to create a object using a constructor function, so let's remove the circle, draw and define a constructor function.
I want you to see them side by side, so once again we define a function, but the naming convention we use for a constructor function is different, the first letter must be capitalized, so we call it a circle. with a capital C, developers with experience in languages ​​like C Sharp and Java, this looks like a class, however as you can see we are defining a function in JavaScript, we don't have the concept of classes so our circular function will be It takes a radio parameter but in the body, instead of returning an object, we will use this keyword to set the properties of this object.
What is this? This is basically a reference to the object that is executing this piece of code. Look at that in a second, so imagine we have a new empty object in memory. Now we'll use this to reference that object and then use dot notation to set various properties on that object so we can set the radio property for this radio argument in a similar way. We can define another drawing property, but this is more exactly a method, so we configure it as a function and here we make a record of drawing points in the console.
Okay, now we can create a new circle like this. We use the new operator to call the circle function. and pass one as an argument, let me use the new operator, some things happen under the hood, this new operator will create an empty object, so like this, an empty object, then you'll set this to point to that object because, of course by default this points to the global object if you are running this code inside a browser the global object is the window object if you are running it inside a node environment the global object is global let me show you so I will make a console let's record this let's see what happens so save the changes now look this is this circular object here and here we have two members drawn and radius this is because we use the new operator here if I delete it let's see what happens so save the changes now this reference is the window object, so this is the global object in a browser, we don't want to use it, we don't want to mess it up, we don't want to define global variables because they are bad practice because they are available everywhere in our application, so It is possible that one function or another may modify the value of these variables accidentally and create a bug in our application, so when we use the new operator to call a function, first three things happen, this new operator will create an empty operator. object will then set this to point to that object and finally return that object from this function, so note that here we don't have an explicit return statement, we won't return this, this will happen automatically when we use the new operator, so let me delete this.
Also, we don't need a console to log in here, so we basically have two ways to create an object. We can use a factory function or a constructor. There is nothing special about this. Both are regular functions in JavaScript if we go back. an object in this function, we refer to that function as a factory function, in contrast, if we use this keyword together with the new operator, we refer to that function as a constructor function. Now you might be wondering what the difference is between these two patterns to create. an object whose focus you should really depends on who you ask.
Developers coming from languages ​​like C Sharp and Java preferred the constructor function syntax because this looks like creating an instance of a class, but again, in JavaScript we don't really have other classes. Developers don't like this approach, they prefer to use factory functions and one of their arguments is if a developer forgets to use the new operator here, then we are defining these property methods on the global object, which in this case is the window object. but this discussion, this argument is really outdated with modern JavaScript and the tools that are available to us, we get an error if we forget to use the new operator here, so my suggestion to you is don't get hung up on these religious arguments about factories. vs constructors as a developer you need to be familiar with both patterns because as you work on different projects and different teams you will see both patterns to create an object so you need to understand how they work, choose the pattern you prefer for each object.
JavaScript has a property called constructor and that refers to the function that was used to construct or create that object, so here we have two objects, a circle and another, let's see the constructor property, here in the console another dot constructor, As you can see, this returns our circular function that we used to create this object now let's look at the circular point constructor, what is this? Well, you can tell this is a function because here we have this blue F and as you can see, the first letter of this function is capitalized, so this is a constructor function built into JavaScript when we create an object using the literal syntax of the object internally, the JavaScript engine uses this constructor function, let me show you, so I will temporarily remove all this code, let's define an object like this, let me use this syntax object literal JavaScript engine will translate it to something like this, let x be equal to a new object, so this circular object we created and returned from our factory function and because we use object literal syntax internally, it was created using this object constructor function in JavaScript we have some other built-in constructors e.g. , we have strings to create strings, but we often use string literals, so using simple code, double quotes or backticks is cleaner and simpler than using the constructor which also has boolean, but Again, we don't use this, we use true or false, so we refer to these as Boolean literals.
We also have numbers, but instead we use numeric literals like 1 2 3, whatever, so this is what I want you to remove. Each object has a constructor property that references the function that was used to create an object. One of the confusing concepts in JavaScript is that functions here are objects, so this circular function we have here is actually an object, don't believe me, let me show you. Look, these are all the members of this circular function or circular object, so the purple icons are methods like calling bind and apply and the blue icons are properties, so let's take a look at some of these members in the console here in the circular point of the console. name returning the name of this function circle length returning the number of arguments Previously in the last lesson I told you that every object in JavaScript has a constructor property and that refers to the function that was used to create an object, but here it is The interesting part, who do you think created this object?
Let's take a look at the circle point constructor, so here we have another built-in constructor called function and let me declare a function using this syntax internally. The JavaScript engine will use this function constructor to create this object. I'm showing it to you, so I'm going to define a constant called circle one two separate from our circle, set it to a new function now here our function requires a parameter radius, so we add it here as a string now as the second argument. I'm going to pass the code inside this function, so to split it over multiple lines, I'm going to use the backtick character and then I'm just going to copy all of this code and put it here so that when we declare a function internally it will be represented like this, now we can call this circle one. it's like calling our circle function so we can create a circular object by renewing circle one and passing one as radius save the changes now in the console let's register the circle look it's a real circular object with these two members now let's take a look at a couple of methods that are available in our functions, so I'm going to remove all this code, circle point, here we have this calling method and with this we can call a function, look at the arguments, the first argument is this argument, here we must pass. an empty object and this will reference this object that we passed here, after that we add our arguments explicitly, so here we have one argument, we pass one if it had multiple arguments, we would pass them explicitly like this, okay, so this expression is exactly the same to the expression. in line 11, when we use new operator, this new operator will internally create an empty object and pass it as first argument to the calling method and this object will determine the context for this, so this will reference this object before.
I told you that if you don't use the new operator, this by default will point to the global object which is window, so if I want to rewrite this expression this way instead of passing an empty object, I would pass window, of course we don't want to do that. This I'm just explaining to you what's going on under the hood, so let's reverse this so the argument here specifies the point of this. Okay, now we have another method called Apply, it's exactly like the call method, with this we can call a function, but instead. Instead of passing all the arguments explicitly, we pass them in an array, so this is useful if you already have an array somewhere else in your application and you want to pass an array as a second argument to the application method, so this is the conclusion in JavaScript functions. or objects hey guys Marsh, thanks for watching my YouTube tutorial.
I just wanted to quickly let you know that this video that you've been watching is actually the first hour of one of my courses called object-oriented programming in JavaScript, so when you get to the end of this tutorial, if you feel like you want to learn more, please do click on the link in the video description and sign up for the course and if not, that's perfectly fine, continue watching the next section on JavaScript, we have two categories of types. on one side we have value types also called primitives and on the other side we have reference types, so in the value types category we have the numeric string boolean symbol, which is new in es6 and we will see it later in the course. undefined and know that these are the primitive or value types, on the other hand, we have objects, functions and arrays, so in the last lesson you learned that functions are also objects, the same goes for a race, so, Simply put, in JavaScript we have primitives and objects.
Now, in this lecture, I'm going to show you how primitives and objects behave differently because it's absolutely important that you understand this before we move on to the next section whereI'm talking about prototypes, so on this empty canvas I'll define two primitives. x and y I'm going to set Y to X, so here Y is 10. Now I'm going to change the value of x to 20. What I want you to notice here is that Back in the console, let's record stored in the variable is copied into this new variable so that they are completely independent of each other.
Now let's see what happens if we use a reference type or an object here, so I'm going to change this to an object that has a property called value and then instead of setting to save the changes back to the console. Let's record X so you can see it through the properties. 20 now let's record Y. We can see that the value property of Y is also 20, so this is the conclusion. when we use an object, the object is not stored in this variable, that object is stored somewhere else in memory and the address of that memory location is stored inside that variable, so when we copy or the reference. copied in other words, both x and y point to the same object in memory and when we modify that object using value reference or the objects are copied by the reference, let's take a look at another example, so I will define a function called increase which takes a number and here we simply increase this number by 1.
Let's declare a numeric variable and set it to 10 and then we will call increase and pass. this number now, if I log this number into the console, what do you think we're going to see? Let's take a look, so we save the changes, we see 10, but at dinner we increase the number nicely when we call increase and we pass this numeric variable to its value. is copied into this parameter which is local in this function, so this numeric variable here is completely independent of this other numeric variable here in this function we increment the number by 1 so that it is 11, but after this function this number will come out of the scope, so when we log this number into the console, we are essentially dealing with this first number, so I told you that primitives are copied by their value, so here we are dealing with two independent copies, that is why we now see ten on the console. let's change this to a reference type or an object, so I'm going to change ten to an object that has a value property.
Okay, let's rename this variable to object and similarly, I'm going to rename this parameter in this function to object and then increment it. point value of the object now, when we log this to the console, what do you think we'll see? We will see eleven. Look, we have this object with the value 11. The reason for this is that when we call increase and we pass this object, this object. is passed by its reference so this local parameter that we have here will point to the same object that we defined here, so in this case we are not dealing with two independent copies, we have two variables that point to the same object, so any change What we do in this object will be visible. to the other variable, so remember this in JavaScript, we have value types also called primitives as well as reference types which are objects, our primitives are numeric strings, undefined boolean symbols and no primitives or value types are copied by their types of value reference nor objects are copied by The reference is fine, so here we have our circle constructor function and using it we create a circle object.
Now these objects in JavaScript are dynamic, which means that after creating them you can add additional properties to them or remove some properties. You may be wondering why this. It is useful in real world imagine you are working with a user object, the client which can be a web or mobile application will send a user object to the server on the server we get this user object and then we add additional things. For example, we can add a token property to it that we generate on the fly on the server, so we can always add something extra to an existing object because we don't have classes, we don't need to define these properties in advance.
We can add them when we need them and this makes JavaScript extremely powerful and easy to work with in languages ​​like C Sharp or Java. Every time we want to implement scenarios like this we have to go back and change our classes, so let me add a new one. property of our circle object, we can set the location here like this, save the changes now here in the console, let's register the circle, okay, you can see here, we have two properties, location and radius. We also have another notation for accessing properties, which is the square bracket notation.
Another way to rewrite this code is like this: we use square brackets and use a string to reference a property, so the location is exactly the same, as we can see, the dot notation is simpler and less detailed than the dot notation square brackets, but this notation is also useful in certain scenarios. for example when you want to dynamically access the name of a property, let's imagine we have this constant called property name set to location, you have it somewhere in our application, now we want to access the location property of a circle if you are dealing with this. dynamically at the time of writing the code we don't know what is the name of that property that is calculated at runtime, so we can write something like this circle at that location, but what we can do is use square bracket notation, so we use circle brackets. property name Another use case for using bracket notation is when using property names that are not valid identifiers, for example let's imagine the name of this property is Center: location where we can access this property like this circle, that Center: location that doesn't It doesn't work, so if you have special characters or a space that's when you use square bracket notation.
Now we can also remove a property from an existing object. A real word use case for this is when you get a user object from a database and you want to return it to the client, but maybe that user object has certain properties that you don't want to send to the client, you don't want to send the password, you don't want to send the credit card information, in that case you will dynamically delete one or more properties of an object, so we use the delete operator and then reference the property name to circle the location of the point again here we can use dot or bracket notation, of course here we need a string, sometimes iterating or enumerating is necessary. properties on an object we can do that using for in loop, so for let key in circle, so in each iteration the key will keep the value of a key in this object, let's log that in the console, okay, look , we have a radio and we draw like this. is returning properties and methods now, if you want to get the value of these properties, you can use square bracket notation, so here and console the record.
I'm going to record the key circle that you learned in the last lab lecture, we can use the notation in square brackets. to access a member, okay, let's say now you can see that the radius is 10 and draw as a function, what if we want to get only the properties and not the methods? We can use the type operator to check the type of this value, so if typeof the key circle is not equal to the function, then we will show it in the console we save the changes now we get only the radius. There is another approach to get all the keys and an object, so the object we have has a method called keys that we can. pass our circle object here and this will return all the keys in the circle as an array so let's store them here and lock them in the console so here we have an array with two radius members and draw with this approach we can't separate the properties of methods. now finally sometimes you want to know if an object has a certain property, for that we use in operator, so if here we add the name of the appropriate object as a string, if the radius is in a circle, we make a console that indicates that the register of the circle has a radius.
Okay, save your changes and here's our message, so remember to list all members and an object. You can use a four loop loop to get all the keys and an object. Use the object key and to verify the existence of a property or method. an object uses the in operator, now let's introduce some complexity in this example, so I'm going to define another property called default location, set it to an object like this, let's also define another method to calculate the optimal location, we set this to a function and here we are going to do some magic, it doesn't really matter, what matters is that we are going to call this method inside the draw method, so we call this optimal point calculation location.
Now there is a problem with this implementation, let me. I show you here when we create the circle object circle dot these are the members of our circle object, not all these members should be accessible to me as a consumer or client of this object, for example what would happen if I set the default location to false ? is going to completely mess up this object or, as another example, maybe this calculate method should only be called inside the draw method, so if I accidentally call it here, circle the optimal calculate location, maybe this will put this object in a bad state and then if I call circle but when drawing we will get a strange error at runtime so in object oriented programming we have this core concept called abstraction abstraction means we have to hide the details and the complexity and show or expose only what is essential in this particular example. hide the default location of this property as well as this method, these are implementation details, they are part of the complexity of this object, we want to hide them from the consumers of this object, instead we want to expose only the essentials i.e. , the radius and the drawing method.
Let me give you a metaphor: think of a DVD player. A DVD player has a complex logic board on the inside, but only a few buttons on the outside that it interacts with, so what we have on the inside are the implementation details and what we have. the outside is the public interface of our player, we want our objects to look like this DVD player, we want to hide all the details, all the unnecessary complexity inside and expose only a few members or a few buttons on the outside, a A large number of developers who have not been able to apply object-oriented programming effectively have not complied with this principle, everything in their objects is public and accessible from the outside and this will bring a series of problems, one of them is that each Every time the implementation of that object is changed you have to go and modify many different places in your code, for example, let's now imagine that this calculation method requires an argument, let's add a factor argument here with the current implementation because we can access this from the outside in all the places where we have used this method.
We have to go back and pass an argument so that a simple change to the implementation of an object results in a series of changes to its source code. In contrast, imagine that if this method were not accessible from the outside, then we would not have to modify this line. I would only modify line 12 where we have correctly called this function, so remember the abstraction principle of object-oriented programming, hide the details and expose only the essentials in the next lecture. I'll show you how to implement this in JavaScript and how do we implement the abstraction here?
Do you want to hide certain members from the outside? So, earlier you learned that this refers to that new circular object. Now what happens if I declare a local variable in this function? Let's say we set the color to red. This is going to be? part of that object of course not because we haven't set it as a property on that object we don't set this color to color okay so this is just a local variable inside this function when we exit this function this variable exits from scope and dies now with this technique we can easily hide certain members from outside so default location is implementation detail.
We don't want this to be accessible from the outside instead of setting it as a property on our new object that we defined. as a local variable here okay, now we don't need this color anymore, in the same way we can convert this method to a private method, so let's let calculate be a function now here in the draw method remembering theoptimal calculation location, this function will no longer be a method on this new object so we can access it using this. You have to access directly here. This will work because in JavaScript we have this concept of closure.
If you don't know the closure, let me simplify it, so here we have it. a function and another function inside that function in this function we can declare certain variables like X and Y and these are local variables which are only available in this function their scope is limited to this function so when we finish executing this function x and y will go out of scope, unlike scope, we have a closure. A closure determines which variables will be accessible to an internal function, so this function will be able to access all local variables defined here, as well as variables defined in its main function, so here we declare two variables to calculate the optimal location , which is a function, as well as the default location, these are the variables that are defined in this main function, they are within the scope of this function, but within the closure of this inner function, now don't confuse the closure. with a scope because the scope is temporary and dies so every time we call the draw method these variables will be recreated and reinitialized and then after this function they will die so the scope is temporary but the closure remains there, so when we call the draw function after we finish executing this function, these variables will continue in memory, they will retain their state because they are part of the closure of this draw function.
Okay, so come back here, in this method, if you want to access those private members, just use them here. You can also use the default location, the default location, but if you want to access the members of this new circular object, you have to use this, so this point radius is an example. Okay, now with this simple change we basically replace this with let's see what happens if I access the members of the circular object, we only see drawing and radius, so the public interface of this object is simpler, it's easier to work with and this It will also avoid problems in the future, so at the last conference we

made

these two members private members.
Now, more precisely, these are not private members of the circle object because they are not technically inside a circle object. There are local variables that we have defined inside this circular function, but from an object-oriented point of view we can refer to them as private members of the circular object now I want to simplify the code here so we can focus on a small problem. I'm going to remove this calculation function so that we have this privately owned default location, we can't access this from the outside, but what if we want to display that default location somewhere in our application, so we don't want to modify it, we just want to be able to read it, so one solution is to define a method here, this point gets the default location, we set it as a function and in this function we simply return the default location once again, we are dealing with an internal function here, the closure of this function includes all the variables defined here as well as all the variables defined and their parent functions, so here we have access to the default location and with this we can call circle dot to get the default location, however we don't I like this syntax.
I don't like the fact that we are calling this as a method. It would be better if we could access this property as this default location, but we shouldn't. We can't set this from the outside, we can only read it, so let me show you how to define a property like that. This object that you have seen so far has a method called define property. We have another method called defined properties. we want to define multiple properties in one go, now the first argument of this method is the object to which we want to add a new pretty; now the object is referenced by this new circular object, so we pass it here the second one.
The argument is the name of our property that we want to call to that default location and the third argument is an object in this object we add a key-value pair, the key is get, this is a special keyword for JavaScript and the value is a function so when access default location of circle point this function will be called ok now here we can just return default location again this variable is part of closure of this inner function so here we can access it right now in the vs code, you don't see that in intellisense so we don't have the default location as a property, however if we save the changes, I

made

a mistake here, actually I should have used the defined property, so save the changes fine, like this so now look at the circle of the circular object so here is our new property.default location you can see dot dot dot in front because this is a calculated property when we click on it the get function will be executed and here is the result our default location is fine, you can also see that the function is stored here as a getter, so getter is a function that is used to read a property, so this property we have here a default location.
We refer to this as a read-only property. If you want to set the value of this property from outside, we define a setter, so in this object we add another key-value pair, the key is set, which is a special keyword and the value is a function. Now this function takes an argument called value. We can set this default location which is value, but the interesting thing is that because we are using a function in this function we can perform some validation for this value before setting the default location, for example we can write some simple logic like this if value Now we can come here and set the default location for Circle Duck.
Let's see what happens if we set this to 1, save the changes and here is our invalid location error so to recap, use the object in define property to define getters and/or sellers. This is a great exercise for you. I want you to use what you've learned in this section and design a stopwatch object like this, so let me show you. How does this behave? I'm going to define a constant called SW and set it to a new stopwatch, so that's our stopwatch object. Now this object has some duration members, which is a property, as well as three methods to reset start and stop, and the other members you see here are inherited from the base object.
Well, initially the duration is zero. We can start the stopwatch now. At this time, if we call start again, it will yell at us. The timer has already started, so we can't call start twice. Now we can. call stop and again we can't call stop twice in a row, it will complain because the stopwatch is not starting now we can access the duration property, so the stopwatch, oops, sorry, stopwatch point duration, so this stopwatch counted 19 seconds from the time I called the start method to I called the stop method now we can repeat so if we call start again now it continues counting and then we call stop and then see the duration again now it's a total of 20 seconds, we can also call reset and this takes the stopwatch back to its initial state, so we can call start and then stop and then look at the duration of just 2 seconds, that's how this stopwatch works now.
I want you to go ahead and spend about 30 minutes on this exercise, use what you've learned and do it. the best you can do is implement an object that behaves like this in the next conference. I'll show you my solution, okay, here is my implementation of the stopwatch object. Now don't worry if your implementation is different than mine, it will most likely be different because there is no single solution for a given problem as long as your stopwatch behaves like what I showed you in the last lecture and has an implementation clean. Your solution is perfectly fine, so here we have a function called stopwatch.
This is a constructor function I have. I defined some private variables here, start time and run time to see if the stopwatch is running or not and the duration which I initially set to zero. You can see we have three methods here, start, stop and reset, and I have also defined a read. only property called duration, look here, we have a getter that just returns this duration, which is a local variable in this function. Okay, now let's take a look at the implementation of each of these methods, so let's get started first, we have a validation check if the stopwatch is running. we simply throw a new error with this message the timer has already started; otherwise we set the run to true and set the start time to the current time of day.
Very simple implementation, the stop method is very similar so first we have a validation check if it is not running obviously we can't stop it that's why we throw new error otherwise we set run to false , then we set n time to the current datetime and then calculate the second between the end time and the start time, so we call n time to get the time and subtract it. from the start time, get the time, this expression returns the milliseconds between these two date objects, so we divide by a thousand to get the seconds and then add them to the duration variable that we defined earlier and finally let's take a look at the reset method here just set these variables to their initial value, so we set the start time and end time to null, running to false and zero, so once again if your implementation is different it won't be worry, there is no better solution for a given problem if I come back and solve this problem within a month.
My implementation is likely different from what you see now. Hello, it's me Mash again. I wanted to thank you very much for watching this tutorial to the end. I hope you have learned a lot, please. share and like this video to support me if you want to learn more about object-oriented programming as I told you before I have a course called object-oriented programming in JavaScript this video that you have been watching is the first hour of that course if you want to get For more information, click the link in the video description and sign up for the course, if not, that's perfectly fine, make sure to subscribe to my channel because I upload new videos every week.
Thank you and have a great day.

If you have any copyright issue, please Contact