JavaScript The Hard Parts: Object Oriented Programming

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this video on object-oriented programming in JavaScript object-oriented programming the notion of wrapping our data and functionality in objects is the heart of many modern programming languages javascript gives us the ability to emulate many of those features as well but to do it properly we have to understand the distinct implementation style of JavaScript object-oriented programming and we're going to discover that rests on understanding features like the prototype chain like this Dundas core proto Dundas core reference get those down and the meaning behind the class keyword the new keyword all those favorite questions in seasoned developer interviews become much more accessible to us so join us in this video as we go deep on how Opie works in JavaScript and become the proficient developers who can implement those features in our own professional code object-oriented programming a hugely popular paradigm of writing a code at scale well I'm no longer writing a hundred lines 500 miles a thousand lines of code but instead tens of thousands of lines of code I have hundreds of developers working on my codebase with me I need a way of structuring it of organizing it that is a couple of things one easy for me to add features and functionality to it maybe there's another developer without breaking what was already there to when another developer picks up my code they can reason about it and sort of see the layout and easily understand what's going on that's opposed because it follows a certain set of standards but hopefully also because it's structured in a way that is meaningful given the needs that I'm gonna have my codebase we'll see what that means later on and finally that it's performant is my means or structural my code going to be efficient is it going to allow me to do as much as I can without taking as many steps as I can or without using up inefficiently a huge amount of memory space at the expense at this expensive performance so object-oriented programming says let's think about what we do when we write code essentially we do two things we store data in memory and we apply functionality to data in his heart that's what we do in write code we store information data and we apply functionality to it now don't be wrong it's really complicated with lots of different functionality and lots of data but essentially we are writing functionality and data I'm applying for clarity to data think about a user who is well at school in a quiz game I'm going to apply the functionality of increasing school to that users school data the value of their score given that our object oriented programming paradigm says okay what we're really doing is just writing functionality to apply the data and there's lots of functionality that applies to this bit of data there's lots bit of data could we somehow think of that challenge in terms of some structure and what might that structure be we're going to see in a second now I will tell you this whereas with our functional programming our high order functions those we can very quickly see with a single function how valuable it is it is very easy to see that map copy array manipulate makes the life of writing out copy array x - copy rendered by budget grab much easier than writing for those functions out so we instantly see the value of parsing in a callback function and additional instructions and the calling of the higher-order function our P is not as easy to see its inherent value until we are dealing with complexity of scale so we're gonna have to play a little bit of a sort of imaginary game or building an application and scale a little quiz game it's gonna have users and there here we only have two users named will score three named Tim score six but imagine this thousands of views it's all playing simultaneously with many many different data net many different properties associated with each user a score and avatar you know a home page a time zone a login state or a logout state all these were pieces will attach to each individual user and a ton of functionality that can be applied to each of these users here we've only got the ability to increase score but we could you know log in log out change habits are an avatar to beat avatar delete profile hundreds of different pieces of functionality that every single user Roberto said code is about writing code is about writing functionality to apply to data every single user all this data we want all that functionality to be available because if all I'm doing right when I write code is applying functionality to data well they wouldn't it be great if all the functionality that I would ever want to apply to this user data is there right a Jason somehow we'll see what that means but somehow packaged up bundled up so that I know always that the relevant functionality will be there for my relevant data what would be the best way of somehow wrapping bundling up the relevant functionality that could ever be applied to the pertinent data at that moment or how could we bundle those things up Louis possibly in an object and that is the heart of that object-oriented paradigm it's saying the best way to structure what we're essentially doing a right code which is applying functionality to data the best way to structure that is to bundle the relevant functionality and associated directly with the relevant data in objects know that we can have a whole bunch of different relevant functionality and in reality hundreds of these different functions but in essence we are storing functions with their associated data on objects so that we can do this thing here um and if we can do this thing here we are so happy if I can run my relevant function in this case the ability to include the score of my relevant data the user one school property then I am so happy this makes my code super easy for someone else to reason about where's the relevant functionality for this user object oh don't worry there it is associated and I can just run the function right to the right-hand side of the dot that goal of having my functionality and data bundled together everything we're going to see today is going to be about achieving that goal can I get my relevant functionality on my relevant date if I can do that everything else follows that's going to be my fundamental goal the whole rest of this session I'm going to start very simple way of bundling with and data together literally created one here by wrapping them using object literal we need to find a fun object by itself it's called an object literal we're going to discover there's more and more sophisticated ways and what we do in certain early versions there's trade-offs as costs of doing it that me yes it's very and true it's very simple again goal object containing data and functionality bundled as one but there's going to be big downsides but we're never gonna lose sight then our fundamental go on the entire session is can we achieve calling the relevant functionality on the relevant data for example user 1 dot increment is my functionality right there to the right hand side of my data this is an encapsulation binding together the data and functionality that manipulates that data binding it together in a bundle is known as encapsulation we're going to see a couple of ways of creating objects as we get familiar with a few different means of defining our objects was another way here I've declared a fully populated object literal scarda what's other way I can I could have created this user one object you could have set an empty object and populate it with what type of notation dot notation yeah exactly let's see it it's all notation create an empty object and then assign its properties using dot notation let's just do this one talk through it line by line to make sure we're clear skyla so first I'm going to declare a variable to do yeah set that equal to an empty object yeah and we're going to access that of the object and store a key with name yeah that's a sign to the stream Ken yeah then we're gonna acts the same object scores they said that two-six right you do not know this very well yeah six exactly yeah and then we're gonna add function on this key which is called method yeah exactly you command which their community yeah so our increment property known as a method as a function exactly excellent now are we call jaegerman here no no it is a fine designing let me fill out what our properties excellent now you said we could also fill out the square bracket notation I want to stress bracket notation is never used to except in one title condition what is that one by the condition lewis when you trying to evaluate what goes oh well you're talking about body weight what's going to be the property yeah exactly well I want to essentially leave so user to I can have I don't know property and then this is a unknown right now it's going to be evaluated when I hit this line and I'm looking memory for property and find that maybe property is name so this is where I want to over I want to leave it on Infinite's a variable on a zero have my property to be determined at the point I hear that line so it's about handling variables that are going to then evaluate to an individual property name and no other time now if your property name has a space all begins with a number or a special character fine you need to use you know square brackets to do - I can't but if you ever have a property name that is that you've got bigger problems than using some where bracket notation so you're never going to use square bracket except for when you're always in the unit which is with variables all right tal notation who can tell me another way of declaring an object it's going to declare an empty object is using a built-in feature of JavaScript meter you know another way of create an empty object object hey there's the object or create fantastic need you to spot on that's exactly it using object create well this line here at the top here user 3 or tummy Philly what's it's mine it's hope you're going to do it's going to create an empty object user 3 is set as a variable on the left hand side and it's going to have assigned to it the return value hmm return back to ensure it's where it's saying that I'm people create cool is going to return an empty object it's going to keep us out of this an empty object now you see them now being passed in we're gonna see that you can pass anything I mean want some object in with a thousand properties it's still always going to return us an empty Bolger by the end of this top line here we have exactly this thing as a top line here user - is any object well with a slight under the hood difference we're going to see later on user 3 is an empty object so keep talking through it for it and then we access the user 3 object creating a property named Joe and assigning it the string IVA yeah same thing fax us the user 3 object giving it a score property and signing at the number 9 and then accessing the same objects and getting anything couldn't property and getting it a function yeah so the method what are we noticing here we handwriting out of our objects here is this is this sustainable know what we're doing something very repetitive see what we do when we have repetitive code what do we usually do to avoid repeating ourselves right we write functions functions are what save us from writing things again and again functions are wrapping up instructions to then be used over there general enough that can be used for each each circumstance it can be used again and again right than once call them many times very proud of that it's wicked millions of use we caught me having the developers handwriting out each of the user objects behind the scenes as soon as you start playing I always imagine that no we can't do that we instead wrap our creation of an object in a function and then we can run that function and fill in the individual properties and then return out that object and store it in a variable this is our first solution if all we want to do which we do is be able to run our functionality are relevant functionality relevant data news one represents our relevant data with score property in name will score 3 and then add relevant functionality increment data for Gallardo is that then this is going to solve our problem solution one is going to be a beautiful solution super intuitive but it is going to be fundamentally unusable but we are going to see it so we can understand why it's fundamentally unusable buddies so it's doing its job it screen objects with data and functionality bundled together so it's doing its fundamental job like one let's see it's to its job Schuyler what are we doing in line one so the query function user created use a creator with the parameters name is good perfect there it is there's a function next line Z we are declaring there yeah user1 excellent now do we know what's gonna be sorted yet undefined undefined who's gonna be the return value right of calling what user user one will be the return value with calling user created with what argument see well and perfect will and three all right I company would still have my name on this muttering sighs years ago all right so we create everybody eight this will feel good create a new execution excellent a perfect all right there it is xington context and in we go and what's the first line of code say to do inside of this execution context well the first thing we do we want to handle first Louis inside this user context we have a parameter name we're saying it's variable well the argument yep then we have the parameters floor it's gonna be the right event great now you deploy the function what's the first thing you say to do we're gonna create an object yeah yeah good inside a wall properties probably name that the value well yeah the name argument right yeah so new user that exists it's an empty object dot name says a property name and have assigned to it the name argument the name argument that was stored in memory at the point which we fill the name argument in with will so don't confuse a name here in the the name or the left hand side is a new property we're creating the name of the right hand side is referring to in retrieving from memory the argument with the Vani will okay good can be going okay news repeating on properties corner with evaluate yep and then we're creating him at the coffee minutes with function division okay final function we are returning the new user object returned out into global memory where it is stored in water wearable user 1 user 1 there it is perfect so now user 1 gets filled in no longer under fire gets filled in with this object name will school 3 and increment is a function we achieve the same thing we did when we hand wrote the object but now we did it with just a single line user creator function being called returning an object perfect now I'm not going to go through the entire next one but we've now returned out to global where the next line is wort for it the next line is declaring a user to write setting it equal to calling user creator passing in ten and five yeah so it's going to be set to equal to be evaluated return well the return value of user Creator cooled with the arguments Tim and five and that's going to return out I'm not going to create the entire fusion context but it's gonna return Walt an object with a property named Tim score three and then an increment function yeah a brand new all of these were created inside of user creator just like this but we just not going to copy however again I'm clear on that we've got inside this we create an execution context we didn't do all the stuff inside of it but it's all being done and out returned this object into global memory under the label the user to named Tim score five and increment is a function and so now we're going to test can we do the thing that makes our lives as developers so effortless can we do it Louis can I do user to increment being invoked talk me through it if I can do Mikey test or whether my code is doing its job talk me through this process object and it's a function so I can successfully execute my function code fantastic my job is done by Thomas darling I really want to do I'm generating objects containing data reporting as he attached and I can run my function on my data am I happy no Z what am I not happy because you're making the same password for every single object he spawn he's exactly right this is a beautiful benefits not beautiful solution this is it's a simple solution it'll beautiful this is a simple solution but it's fundamentally unusable we can never we will never ever use this solution ever in practice this solution returns our objects each of which have a brand-new increment function defined on them now I'm not gonna have one function attached to each user object I have a hundred five hundred I want to be able to add login functionality logout functionality render user I wanna just do anything I want and each of them gonna have a copy of that function maybe it's four hundred lines in the function 50 lies in the function and I've got a hundred functions and I've got ten thousand users I'm a you know 50 million lines completely wasting the space when now don't get me wrong we'll free Tim right there they're different I need to say separate space for each of them but these guys are not these functions are exactly the same and yet each time I create a new user we make space in a computer's memory for all our data great and functions but our functions are just copies is there a better way what will be a better way intuitively Louis to somehow not have a copy of each function function on each object all being intuitive better way of doing it perhaps creating an object that holds all your functions an object that holds all my functions single copies of them exactly and then somehow when I hit user to Don increment nobody looking and it turns out jobs it gives us a beep a built-in feature to do exactly that anyone know what it's called don't shout the title the dog good we'll do a run at second all right solution to it's gonna be so all that increment function all the functions we want each of these objects that have access to on the on the dot on the right-hand side of the dot has kind of methods in just one object and have the interpreter that's the JavaScript engine as it runs through our code if it doesn't find the function increment on user to on user one doesn't find it on here there it's not here doesn't find it somehow it knows to go and look let's call it function store in some shared object where increment is happily sitting around somehow it knows to go looking there how to make that link javascript gives us a built-in feature of its own design that lets us make somehow a link to the shared function store so the Java can automatically go to look up there without any sort of process from us it's going to good looking up there automatically without a time you'd expect if I go and look there well we will but nor nor the movement of the line gets run and how does it do it uses a feature of JavaScript known as the prototype chain this bond is going to be called a prototype of a prototype or bond it's gonna be a chain link up to here using this feature of jobs will pull the prototype chain to ensure when it does not find increment on user to is a panic it knows to go looking on function store what does it find but the increment function so how's that going to work having that link the prototype chain using the prototype or nature of JavaScript here it is a solution to in full we're going to walk through it line by line and we're going to discover a way to make some bond to this shared function store all right okay here we go line 1 z 1 z 1 z my onesie Howard's a clang punching I'll use their creator I was very professional like onesie okay all right okay good line 1 z we declare a function use creates a spot on there it is use a creator excellent stored in global memory line 2 meter we're declaring a variable okay nice use a function store perfect into which we're storing there it is used to store all right next line Luis so we're declaring a variable user one will remember idea Santu the return value of running user creator with the argument well it's another five - now there's gonna be the return value or running user creator with the input of will the arguments will and three create everybody and execute a great beautiful it was mellifluous there we go and in we go and film it what's the person's inside we take care of our parameters yeah name equal to will yeah it's for you or three very good and then next time oh now if it's interesting what's this first line the body of function tell us to do what's new user going to be off its very first line Phillip it's going to be an object absolutely and new user here it is new user is equal to object create pass in whatever for some reason we're passing in this functions misuse a function of sort who knows why we'll find out a minute what does this return out fundamentally Phillip an empty out an empty object and discover has some hidden properties but it is fundamentally an empty object that gets assigned to walk finit new user new user excellent there it is next line Scala so we're gonna access that new user object yeah I'm gonna add a key name equal to the I grant passed in name first of all right well put Scott a yet and then do the same free score is everybody okay and then follow the line of the function we're gonna return for their return the body of new user feel checked in to walk global variable into corneas into user one recording is it returns out this new user object or this object that's formerly known as a user into the global variable user one perfect thank you Scott can we do all hallowed thing of running on user one the all-important increment functionality can we do this talk me through it medium left-hand side first well okay so on the user one Objectivists yeah do I find the increment function no I do not hmm any idea why would we do so much and then it fail turns out that when we declare that empty object we made a special bond before we return down to user one we made a special bond to use a function store when I rat when I create a memory object using this object or create method and parsing use a function story was saying make sure this object stored in new user could get somehow a special bond to this user function store object over here where increments sitting happily be a special bond over there meaning when I returned out this new user into user one that special bond and don't get this confused with under special bonds we have like the other ones from closure or other areas this is a different one so the special bond up to that user function store meaning median talked me through what actually happens here so it's going to find well it's got to look in that special place okay well we're gonna come to that in a second and up he goes to these user function store where it finds increment and it's ready to run it and execute see it creates an execution context exactly to run that code now you can use the question though here's a question how is that special one mate well I'm absolutely standing by that this is an empty object at the point at which optional created is returning the handy object by some lame but it isn't the object with a special hidden property now it's not like our double square bracket scope property we can't see we can't dot you know doctor quite a console.log this is what we can see if we were to console.log got a new user object and press the little down arrow we see a bunch of hidden properties one of them is double underscore proto double underscore there it is underscore proto underscore which is justin pink underscore proto underscore which is a bond is a hidden property we have two console.log news at the present down arrow to see in the console to see the hidden properties one of them is our honors and when we declare our empty object using the object or create technique which we notice gracing the object but it gets this hidden property underscore proto underscore to whatever we passed in which was user function store a bond up to use a function store and that doesn't go away so attack them to return that object out into user one you return it out into user one the output of user Creator which are not to use one it still has that underscore proto underscore bond to use a function store there it is underscore pro two Anna's for bond so what happens is JavaScript has a built-in feature called the prototype chain meaning when I run user 1 dot increment and I go and look for you to want success and I don't find increment as a method a function on it I don't panic Java strip is automatically not going to give up when it looks for something object and doesn't find it because it's got a go to that I know underscore underscore and see what's there use a function store hmm interesting as soon as he wasn't it and there's increment function ready to go and then we create execution context with it and this same function would also be available to we're not going to run through it the whole way but what would we looking at our code there what would we think user to is going to have stored in it after calling user Creator with Tim fire two and five Louis well what's the overall thing has the property name the sanctity and yep I'm pretty asked were sanctified perfect so we just we've skipped over the running of the user creator function and said when we call use greater its return value will be this object here stored in user to we didn't walk through the entire institution contents but it was happening of course what does this guy also have attached water hidden property together the underscore proto underscore hidden reference to use a function store there it is so I can also run user to use a 2 dot increment let's do it talk me through the process see if I run use a total increment which takes you to the user functions story I think about perfect and I take that code and I'm gonna make an execution context in which to run it all right so when I do that and I go this increment function clearly needs to be usable on whatever object I run it on and what that means is I need some placeholder inside of that function increment in order to refer to that object whether it's user 2 and I run increment on user to or user 1 when I ready go to user 1 well I need to go to refer to that object somehow from inside increment I need a default label that's always going to refer to the object in which I'm running the function don't tell me what that label is Skyler the SKU blurred least exactly I'm gonna have this keyword by default here's our fundamental always pointing to the relevant object to the left-hand side of the dot on which I'm calling this function if you object to the letter type I'm calling increment on the right hand side of the user to object and therefore inside us at the execution Cartesian context the this will be automatically bound to set to user 2 and so now I can make sure I can refer to the exact object I want to refer to and my increment function is nicely general it can be used on any object it's because I've got one copy of it so we need to be usable more objects that would be returned out of user creator so what is our line of code inside increment skyla two accesses or keywords of this value aha increment it so this tall exactly so what is the list of school bus what's going to evaluate to for user to last coladas bus use a 2 dot school plus plus now where is user 2 if I don't get my local memories that use it to know so actually it's not advisable to skip one out findings or to find the school property incremented to 6 beautiful my increment function has become true D general but I had to use this business built-in this keyword that's gonna give that first rule for I'm gonna see another over in a minute our first rule for it is always point to always refer to the object to the left-hand side of the dot on which that function method is being called an execution contacts have been called the right-hand side of an object then which we refer to the method on the to the object on the left using the dot this relationship here the this is going to be bound to the object on the left hand side the dot as a fundamental rule we will see another way that this key quite differently in a moment on one of our later solutions but look our first solution has been very successful we've used the prototype or nature through this underscore proto under school bond note by the way this does not say prototype this user function store is technically known as the prototype of user - the prototype of user one but look at where the bond is stored he's not sorted to be called prototype we're gonna see a different property in solution 3 called prototype fair and helpful in my view but this bond is stories with an underscore proto underscore and we use that feature to be able to achieve our fundamental goal but look now there's no problems with this guy this is a beautiful solution it's super efficient as well man we have do we have any copies of increment stored on user 1 user 2 none instead we have one single copy that function another function again with many took minutes important here and we can refer to them using this prototype or feature that means Charla triple knows to always go check the proto and see what's there and by the way look how easy it is for us to add functions up here which will then be accessible to all the objects even we had a major honor code rather than having individual copies of every function on individual objects very very inefficient okay beautiful thumbs on this second approach you lost me unclear I have traffic Asians all right everybody thumbs up this is a beautiful solution this is a solution in my opinion and no problems it is efficient maybe a little bit long-winded once you start thinking in terms of wrapping your data and the relevant functionality in objects you do it for everything even there's only going to be one instance of it like a game board on which you play the game and we won game board maybe running at a time you still end up producing it as an object returned from a function in return it as an object with the relevant functionality for the game board and the data of the game won't bundled up together so as you start thinking in object-oriented style you do for everything and so creating the object inside by hand cream your dreads inside and then making the bond to the function store by hand and returning it out in other languages we don't have to do that all by hand now the language is all that is handled for us automatically we get the child to do that automatically in JavaScript as well using something well using a keyword that we're going to insert here Oh what could it be what could it be and this keyword is going to automate so it's a lot I think automate it's going to behind the scenes insert so many of these pieces for us what is that keyword do we think Z that we would reinsert it all this superpower I think that's no this is a new keyword I'm glad I'm on the right on the other ii it's a new keyword a new keyword is going to automatically the new keyword we call this by the way the object that there's a function that returns objects is called the constructor function constructs objects the inserting new keywords going to automate multiple things one it's going to automate the creation of this new use this new objects and automate that for us this all will be handled by by the new keyword everything in red is replete me not to write anymore it's good to do all of this for us everything in red and it's going to return the the news object everything's gonna be hard for us automatically the new keyword okay we're gonna see humans support immediately what this might do it automates all of our manual work it automates the creation of the object and then it returns mates or 20 of the object as well into user one just by inserting this new keyword the new keyword just basically does a bunch of stuff inside the execution context for us who can see them how this might require a little bit of rethinking of how we write the code inside of this function for I just curious on how we're gonna create the bind that underscore okay how we gonna make the bind make a link to the user function store yeah because we did that manually right by declaring Arab Jews in ordered or create a party in function store we made a bond to that function store okay so somehow we need to make a bomb to a shared function store well child remain at one for us well that raises the question do we get to set what that fukk where that bunch of stories do we get to call it something all this JavaScript instead choose a place for us to have these shared functions stored and we got to use it well it turns out it chooses a place for us Muse want to use it okay we'll see at the moment what's another challenge that we only so well rethinking is required in terms of the internals of this function now that we manually know now we're no longer manually declaring new user is and the property name to new user object immediately what can you see so we're not gonna have new user right our object is being made for us automatically so we can't refer to it anymore the way we were before as new user name instead we're gonna have to refer to it Johnson's gonna give us a default label for it Louis what's a default label it's going to fall back on it's this very different than we saw earlier inside of increment where it's referring to the object and the calling about method this is a totally different use of the keyword this that this here refers to the auto created object inside of the user create a function because we use a new keywords can automatically create object and give it a label this alright we're gonna walk through this all line by line but it's really require one other thing for us to understand before we move on a funny old notion oh man this is a funny thing how JavaScript thinks about functions as both objects and functions oh man this is funny okay so we're gonna come back to all of this in a second to understand first thing I said is we do not get to set then our functions are the shared functions but all the objects and get returned out and running user Creator each time all get access to through the proto reference we don't get to say that these user functions store anymore all functions so we call it we're gonna set that anymore that's done automatically for us so jobs your says you know you don't get a set C I'm gonna put them in a default place I wouldn't expect you to put those shared functions in a default place probably objects right so we could put a bunch of functions and properties and objects where would that be where could I put where is that gonna be well it's going to take advantage of a funny old property of JavaScript which we saw in our functions that all functions in JavaScript are actually really just objects that can have properties on them like any other object let's see that with a favorite function suppose I declared x 2 and then I call it a sister Claire over here declare x 2 as a function right you know this stuff cool it like this it's gonna return out median you know what I can do or I can do it anytime I can also store on it x 2 a property I alone school and set that equal to 2 and then can I do me don't I do this sure yeah so if you return that 20 I treated my function as an object I treat it as a function and they are absolutely simultaneously acceptable you can think of this some people think of this as x 2 is really always as an object but with a special ability a special ability to be cooled which is essentially running it's called property it's really just an object but a certain ability to be cooled that's the running as a function I don't know if I always love that what I prefer to think of is x 2 has a function version and it has an object version and we can add properties to its object version score is 2 and that does not prevent it also having its function version but you could think of the function version is being like a secret cool property that's going to run the functionality but I've treated at the function by putting friends on the end I run the functionality when I treat it as an object by putting a dot on the end of it I get access to its properties these are living simultaneously they're not in conflict they don't overwrite each other well that means oh damn we do have a potentially useful object in which we can stall a shared functions and that is actually exactly what we're going to see happens is that all functions by default are also objects and all of them have by default a property on them known as prototype it's a regular property on an object which itself our way for this is another object in which we have nothing currently but in which we could store all of our shared functions we're gonna see this play out but just now know that our functions are both functionality that can be run and objects on which properties can be stored and by the way one of those properties by default is called prototype and we are going to know the Bhasin object by default and we potentially gonna store some shared functionality and that little guy there all right let's do this line by line let's go through this with precision but remember we're just looking for a nice place we're looking for a nice place in which to store all of these shared functions and wouldn't be great if we could use user creator in its object format and then somewhere in that object store those functions we're gonna walk through this very very precise around my life and then see our final solution here all right so more complete on this this time so whenever we declare a function yeah okay excellent but more than that when I declare the function use a creator I declare its function version but what else do I declare muted by default is also an object let's make that object it's also an object if we treat it as an object now what do we say by default that object has on it as a property prototype it's not something fancy it's just like a regular property prototype we could even overwrite it say it's a three no use for but it's just a regular a regular property which is there's the key what's the value Louis a prototype what did we say the value of this prototype property was not quite further it's an empty object it's an empty object I can have all the properties I can add all sorts of we said hey what do we have school before I'd have another property on user creates a user grade Adult School could be the school number three whatever but I've got that I've tried that myself but the default one the default one that all functions have in their object format is a property called prototype that's an empty object so far by the way this here has all happened by just declaring the function user Creator it by default is also an object which by default always has a property of local produce I think specialist you know that probably string prototype and it is by default and large large an empty object by definition it can be a large of DOJ goods every object ready to take whatever you want to put in there oh wow I mean this looks like a damn useful similar place to our function store that we had earlier I wouldn't be nice if we were to run user creator and the return that objects would have access somehow to this function store we used to manually created to make the bond do it manually now either default place and we know jobs what's going to be go looking it turns out that if we use the new keyword when we use Creator the objects get automatically created inside and automatically returned out there underscore proto underscore bond will be up to this guy and let's walk through this with clarity Oh given that look what we're doing we're instantly putting some stuff in there so meetin what we put in taught me through a little bit fancy talk me through word by word what's happening here we've declared user created we've not gone inside of it it's automatic got a bunch of stuff on its object version and now we start making use of those taught me through word by word here medium so we're looking at these are creator function yeah we just got my green tracking pen okay we're looking the prototype property which is it's so so far by the way we've been referring referring or creating what do we do we hit this word here so we've been referring to use a crater where we refer to the prototype property and then what are we referring to log in here we referred on when we creating log in at this point oh we are actually exactly and that's the funny thing about this is when you see that used to create an operator's I don't know which bit of this was already here in which there wasn't user created was definitely there perlite was definitely there noggin was not there so what do we do we create it I decide to it it just consoles blocks login I think we might have left behind one method as well increments has been all right there it is increment so we okay I see yeah oh yeah it's good user greater is referred to we end up for the prototype property on it there it is which is a big already object into which we now store the okay we're assigning the property increment both to it and assigning it that functions by the method there it is excellent next line meet you going to these are creator function we're going to its prototype to use read function means object motion and then we are creating an additional property called login and the function fantastic as a method fantastic we've not run any function yet but we've got a whole bunch of stuff now here's stored and we kind of in the end achieve what we did before we have a use credit function and then we had a function stored remember with object object for the function separately but now we're putting it right on the function itself it's kind of set a weird place to put it I realize because man it feels like they're gonna be attached to objects and get returned out but it's just a storage place this is a storage place table trip is going to go to by default all right so next line now Luis for creating a user one okay and then we're calling new user create okay so for now it's undefined and so now we're going to do a key piece user one is going to be the return value of running walk function nice use your Creator yeah perfect yeah a note we aren't running a function here this is not some like special function nanana it is just a function but we're going to mutate its behavior inside using what powerful P word the keyword the new keyword exactly which is gonna insert a bunch of stuff into this function but for now we're gonna create a body we actually a function in you execution context execution context fantastic there it is a new execution context with a local very good environment or local memory you wanna call it okay first piece we're gonna do is handle our arguments Luis handled the arguments for me so first parameter name is going to get the arguments either great or second powder scores the argument nine perfect okay here we go now the new keyword shoots itself in and starts doing a bunch of things what's the first thing it does for it creates a empty object and the object okay give it the meaning this that spot on it's going to create an empty object for us by default and in order that we can refer that in the object nor does that add properties to it we've got to give it a label and that label set for us by default is the keyword this we don't think of this sort of a bit like we had before this is equal to object don't create which we know returns out and add object but it doesn't just do that what else does it do for that object well that's an object yet it's a bind it gets gets be canceling by talking to use that to refer to one of this keyword refers to so it's getting up I guess a bond a connect a prototype or bond through the proto reference it's getting a bond so I'm using the same word it's getting a bond to the shared function store and where is it defaulting to that shared functional store being found the prototype of user-created yeah in other words like property is the prototype object which is a property of user creator in its object format because sometimes it's hoping thing is in the proton has a special mystical place that it's just an object that happens have a portion a prototype who knows why nobody knows all right so it's an ND object but has a hidden underscore proto underscore which is a reference to where it's the user creator add up protect antastic which is this function store objects perfect okay so so far all of this has been done for us done for us by JavaScript without us having to do anything because of what keywords were new the new keyword with great now finally we come back in and what do we do for that we give the this object a property called name assign it to the argument name which is IVA we go we do the same thing we give it a property score and assign it the value is 4 which is not it and now our work is done again so what is the final thing that new keyword inserts Rosemead its returning it it's returning the value of this which is the object looks a lot like object we create by hand before returning this into what global variable user 1 fantastic user 1 is now that returned our object with name is eva score is 9 and 30 dhin underscore proto underscore reference to user create dot prototype which is just the location just the place we're going to go looking for a shared functions so now we ask ourselves can we do our all-important z of user 1 dot increments is how functionality they're available to us on user 1 talk me through it word by word Z well I look for user 1 we look in the memory use don't want to avoid it we do not find the function oh I do we find about to increment on user 1 therefore we go to your browser which is linked to the user creator and then we look for both sigh great and there's an object and then for that do we find it yes we do and we grab its code and we start running an execution context of that code we've achieved everything we want to do we have a beautiful available function to us on our relevant data we can do this on user to user 3 users 1000 but man look how much a new keyword handled look how tight and night and tidy out CODIS no more making of that object by hand oh what a good thing to add so what it's basically passed into object or create here by new user created opera time that object exactly that object of shared functions we want each of these objects gets returned from calling use user creator to have access to now know one thing if I ran user creator without the new keyword do I automatically created this empty object and no right without a new keyword the this thought name is for school what's that this going to refer to John's whenever needs anything on evaluated it's gonna point somewhere very quite region this global object is the window in the browser which is a collection of features of functions of JavaScript but it is definitely not what we want to have the name of school property set on so this is a just to reiterate every JavaScript runtime that means the space which is running has a built-in object full of a bunch of properties of JavaScript called the window and in node it's called the global object when I call a function just a regular function my user Creator with no new keyword and know is that functions are being cooled as a method or an object you can use create something called as a metal object it still has a value for this inside the local memory but this is it's bound as what we do to a bound is bound to that random global object which is of no use at all there's been a very big frustration of people when using javascript and in a way I do think it's a flawed feature that I need to second-guess that the user creates a function requires a new keyword often inside of a user create a function or a quiz question created function whatever actually a whole bunch of new functions to find why my first reference said this will be way down and I'll think I can run the function just good to go see what happens and all sorts of grease that will happen because the lease is being bound to local objects so great anyway so what do we do to ensure we know that that user create a function must be run with the new keyword in front of it Phillip we capitalize the first letter of this is a for design feature that we have to personally come in and capitalize so that I know to run this function but it will not work remotely as I've designed it to work because of the new keyword because look how much size rely on the new keyword to make it work that's a flawed design feature so we step in discharger developers and we run user creator we define it with a capital u at the front and therefore we always developers have developed a sort of standard that we know that's going to require the new keyword in front of it okay folks thumbs on this a third solution we have one more since it's going to prettify it even more since es6 came along but a third solution thumbs on this model you lost me I'm clear I have clarifications everyone stands out all right we are all clear when we think of this model of benefits faster right I have to write less stuff how much jobs who came in to help me still typical practice in professional code this is still increasingly not the standard Whittlesea solution for is increasingly the best practice but you'll still see plenty of code written in this style you will never see solution 2 written and yet knowing that solution 2 is what gives us solution 3 is why you will have the depth of understanding 2 in interviews answer that key question what is the new keyword doing under the hood and even can you build the new keyword from scratch for me because you have every damn piece that goes into the new keyword because you build it from scratch yourself in solution to with object dot create alright so downside of it 99% develops have no idea how it works and therefore fail interviews all right final final solution for takes this and says still this is not similar enough to reduce to traditional object-oriented languages we still need some way in the traditional object or languages we are right now what do we do we did user created dot prototype dot increment is a function use created a product or organ as a function we hand we hand sword them we solve them by hand we stored them in this prototype object by hand in other languages functions that are shared between all returned objects are not stored by hand separately let's just make sure we have our user to what I use it to well let's do our standard one was just named Tim school five and that would also have a proto reference to use a create a dot prototype this guy here okay we are here writing our shared methods the methods that are available all these objects we're writing them in separate what does that mean let's see that means we stalled them associated with user created ready to be available on user one we saw them manually so the language is you don't do that we saw them separately for a constructor we need to find that constr a function the constructs and returns objects and then we separately store the functions on it in the prototype object super explicit stylee's we're still saying exactly where they're being stored well that's still unfortunately too explicit we want to hide even that you want to make a thing even more that under the hood this works like a traditional known as classical object-oriented language even though it fundamentally does not and so other languages let us do this one plesio 3:15 er6 lets us do that also in what's called the class syntactic sugar the class syntactic sugar takes the function definition piece of user creator and calls it constructor it's exactly the same function you see this or name because names sir calls the constructor that sort of subtitle and then it takes the functions that we manually stored user-created operate or increment and how allows us to just list them below and then we wrap the whole thing in something or across and you can call this user create double your class user creator that's all it's changed let's go through to make sure we're really really clear on this because it can be I don't hide it is really this simple it already has nothing's changed class user well we can think of this combination of these two parts class is technically a different data structure data data type in JavaScript but for our benefit right now even think of this as being as being our class so we define the user Creator class comprising its function version the bit that when we call use a creator and we call user creator is going all cool we now call it user cool user is going to run the function version of it bit what subtitle does it give Phillip the bit which we use to call the function version of user crater construct that's a subtitle but it is solutely well I cool they use a creative function with recording the user here but they use grid function it's going to grab that constructor subtitle bit and run that well that's exactly the same that's what I had in version 3 call it use creator and then we ran user creative writing a function version of it but we added to the object version of it these shared functions of a shared function store well here we don't even have to manually do that but know they're going in exactly the same place all functions that I list below this constructor function are all going to be added to the user created dot prototype shared function store they're gonna be out when I write when I added increment and we'll have wrote increment their jobs we kind of pass through this see increment doesn't literally take each of these pieces as it defines it not like later on it as it defines and it goes looks at in gonna grab increment and store it in use a crater don't prototype and there it is and then it sees login and it's going to grab it and store it in user crater don't prototype doc login and then when I run user creator or equally here user when we run it with new what are we doing we're grabbing the constructor subtitled bit the constructor subtitle bit we grab it and we're gonna run it just as before nothing has changed this is why it's called essentially syntactic sugar that's the word meaning our prettifying but nothing under hood has changed now do me wrong class gives you a bunch of new features under the hood but for our purposes here nothing has changed we now have an even cleaner version and even less representative of what is happening under the hood holo good so there's a function use a constructor piece replaced here here's the story of increment and login we just even whatever function does literally semantics honors just throw em in alright so benefits emerging absolutely as a new standard fuels wallets are buying this is almost identical to Python and I don't love this it's like you know not it not owning the fact that Java is very powerfully prototypal language all this stuff on the hood is using the proto references that's not how over P is implemented in traditional ERP languages believe me but I guess it makes it accessible ways it feels similar the downside is 99% of developers have no idea how this works making it inherently challenging to debug it to explain it to talk it through to other developers but you will not be one of those folks congratulations guys that is all of Opie in JavaScript we're there alright thank you
Info
Channel: Codesmith
Views: 19,239
Rating: 4.9874015 out of 5
Keywords: javascript, learn to code, learn javascript, programming, coding, fullstack javascript, software engineer, learn code, web developer, web development, react, redux, node, coding bootcamp la, coding bootcamp ny, coding bootcamp nyc, software engineering, learn coding, advanced coding, advanced javascript, object oriented programming, prototype chain, object-oriented JavaScript, Factories javascript, constructors javascript, classes javascript, ES6 approach, ES5 approach
Id: aAAS9cEuFYI
Channel Id: undefined
Length: 69min 42sec (4182 seconds)
Published: Wed Mar 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.