What is Constructor Function in JavaScript? - JS Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in the last video i showed you what a factory function is it's a design pattern that we use in order to reduce code duplication and create objects for us efficiently i'm bored already you did oh i did yeah oh okay wow in this episode i'm going to show you another native pure javascript pattern that does the same thing but slightly differently and that is constructor functions it gets the name from the constructor function you get inside classes in object-oriented languages every time you create an instance of a class the constructor function is the first thing that gets executed but since javascript didn't have classes for a very long time but it needed the same sort of functionality that's where the name comes from so we sort of get the constructor function without the class itself okay i shall explain this is a 10 part series i'm calling 10 things javascript developers should know but probably don't this is episode four constructor functions let's go [Music] a constructor function is nothing but a function that creates objects for us that's it very similar to factory functions that we talked about in the last video if you're making lots and lots of objects with similar properties or functionality the process can become very repetitive real quick say you have two objects me object and a u object and both of these objects have a talk function on them that announces the name right you should be familiar with this already one says i am cena the other one says i am poli and of course we are met already by our nasty code duplication which we've already talked about so we made this a little better by pulling the name out of the return statement and created a layer of abstraction the issue that we're still facing is that we are duplicating the talk function right right it's like literally a copy of itself we had to write it twice and if you still haven't heard me say enough bad things about code duplication watch any other video in this series and uh yeah then we fixed it using a factory function like this where we have this create person function where i can call the function as many times as i want and all i need to do is pass in the name and the object will do the repetitive stuff for me and return the object back to me so i can do whatever i want with it and remember the name is the only thing that's different between all these different objects the many benefits of centralizing what we call business logic explained here or there or somewhere another way to fix this is using something called a constructor function but unlike factory functions constructors don't actually return the object to you instead the magical new keyword is involved and the mysterious let's just say this keyword there is a bit of magic going on here so let me show you but before i get into some code i want to explain the concept first imagine a restaurant and here's the waitress lisa and here is the chef craig that's that's creepy now these two need to communicate all day and they need to do it very efficiently but imagine if every time lisa wanted to talk to craig and tell him about an order she would have to say hello craig hello lisa how are you today i am good are you ready for another order oh yes lisa who is out there so there's a new table of customers out there and they are very hungry and ready to eat excellent well i have lots of food out here and i can make it for them okay here's the order craig the mom would like a caesar salad and she wants the dressing to be on the side because apparently she thinks that makes a difference the dad would like a crook madame because he had too much beer with his friends last night and the headache is just killing him and the kids who apparently just heard a hilarious joke would both like an avocado toast gluten-free because let's face it this is brooklyn and even kids have instagram well okay then lisa i will make it for them now imagine every time those two had to communicate with each other that they would have to repeat all these unnecessary steps with the greeting and the people and the harmony and the thought process and the all the nonsense all the unnecessary stuff that craig clearly doesn't need to hear so what does she do instead she goes um caesar salad dressing on the side kirk madam and two avocado toasts gf gluten-free or even better she might say something like this number three dressing on the side and number four and 215's gf i don't know why lisa it sounds like she's from queens all of a sudden but you get the point right craig will automatically know what she's talking about because they've established a pattern between the two of them in essence there's a blueprint of communication almost that they both follow give me the items and the quantity and if there is any special requests add that to the end of the order and i'll do the rest and i'll assume that there are people out there that are hungry you don't have to repeat any of that to me leave the unnecessary stuff out of it enough with the pleasantries factory functions which we already looked at are essentially the same idea give me in this case give me the name of the person and i'll do the same and the same idea with constructor functions right we want to create a blueprint for creating objects so we don't have to repeat all the unnecessary parts instead all we have to do is specify the unique parts so that javascript will know what we're talking about and in this game the name is the only variant so let's take our talk function example from before and improve it to the browser alright so constructor functions uh by convention start with a capital letter so let's say function person okay this rule for the capital letter this is not really a rule it will actually work even without it but we're trying to make it seem like we're using classes we want to hint at the fact that this is a constructor in languages that do have classes the class name has to start with typically has to start with a capital letter but for us in javascript we're pretending like it's a class right so i'm going to create a person function and what it does is it it sets a name and actually takes a name and it sets it to this that name okay then what i can do is i can call it i can say const cena equals new i told you the magical new keyword is involved new person and look at that when i try to invoke that function with the new keyword it says hey there's a thing here called name you should you better pass that in and of course i will pass my name all right so there's a lot going on here there's a lot of new stuff here in case you haven't uh seen any of this uh so let me unpack some of that for us so if we first of all if we console log cena we can see that this is already of type person so this is already telling us a little bit about it right but we can also look inside and see there is a name right so this actually created uh the object for us but it's actually when you think about it it's not that different from a constructor function if we if we created an object using a constructor using a factory rather it would actually do the exact same thing for us the only difference is that here i have the object type whereas with a factory function if we didn't have a constructor it would just say object but notice how our function isn't actually returning anything right so how is the assignment of constina really happening here right so when you put new in front of a function call javascript automatically does two things for us first it creates a object inside the function itself and calls it this and then it returns that object this to the statement where it was uh invoked you and i actually won't see any of that but you can imagine that that's the magic behind the constructor function uh that we just wrote here right magic so now i can use this function to create objects without any of the repetitive steps i mean let's actually make it a little more interesting and add a talk function to it and copy this guy let's refresh so if i had this dot talk equals let's create a function here and what this does it returns uh let's do one of these guys hello i am this is that name right so now i can say const cena equals new uh a new person ah refresh let's do that let's forgot to pass in the name okay i can do const ben equals new person let's name ben and then i'll do another one and i'll call it sam right so uh again the beauty of this is that none of the talk function logic has to be repeated no matter how many of these objects i create this constructor function becomes the blueprint on which we can then go ahead and create as many objects as we want in real world scenarios the logic will be a lot more complicated than these few lines so if you don't see the real value here right just imagine if that logic was 10 20 100 lines a blueprint or in the case of javascript the constructor function will be saving you a lot of time and time is monet a real world example could be i'm gonna borrow from the last video is that if you're creating elements and you're attaching them to the dom you can create a function that creates uh dom elements and add very specific content to it it could be even accept a type really maybe whatever you want and then it can return the object back to you using the same method of the this and the new together and then you can take that object and do whatever you want with it so let's create one i'm going to get rid of all this uh let's create a function and we call this super element um remember constructor functions we want to make sure they're pascal case uh but in this case i'm just gonna call it super element because why not it will take a type this might seem similar to you if you watch the episode three uh i take the type and then content content okay and then what it does is creates remember that this already gets created for us so i can add a property element to it document dot create element of type right that type is dynamic i'm gonna pass it in we can have all sorts of logic here what happens if you don't pass the type in and all that but we're not trying to get that fancy today then i can add some inner text to this element and say this that inner text equals content because that's also nope dynamic we're gonna pass that in and then i can even do something cool like add a function to it like add this dot element dot add event listener right you can do that and let's do a click and one simple thing for us to do would be to let's say console.log let's console.log this.l and then after right before i do that i'm gonna add it to the body uh actually document dot body dot add no append right yes up ned append uh this dot l right i think that's all we need cool then what i can do is i can create a const h1 equals new super element right super element parentheses this is my favorite thing about this whole thing is that the browser already knows this guy needs two things you have to send me a type fine h1 and the content hello hello hello uh and that's all i have to do when i want to create this one guy so let's see what happened uh h1 actually you can't see this because my browser this is the one-sided browser the other side you can't see but i'm gonna i can see it that was added to the element take my word for it if i click on it boom it was added and all of that magic is done away from this one line right so all i have to do is just use my constructor function to create this element for me which is which is amazing and then the other thing i can do is i can let me i want to keep this on the screen so i'm just going to copy it i'm going to refresh so everything goes away copy past the quoting jesse warden i see you uh so then what i can do is i can i want to show you what it's like if i create multiple elements so i can of course do const h1 and then h2 and blah blah blah but instead what if i had cons what if i had an array of um array of contents let's say a and then b and then c right let's say i have an array like that and then what i want to do is for each member of that array i want to create an element so i can call super element uh for each of those uh those indexes so what i can do is i can say const my elements right equals the array which is my the array i just created right above i can do a map function here and inside the map function and this will be each item i can iterate through and i can say for each of them return return hopefully you know what array.map does but this is nothing other than me creating a new super element for each of the elements in my each of the items in my array the type i'm just going to hard code this to paragraph and then the second thing which is content would be the actual item which is a b c and so on and so forth so once i do this let's see first was type then it was content cool let's do that and now let's take a look at my elements it created three super elements for me fantastic uh and they're all of type p and then if i just go inside and really if i really want to see what the inner content in our text is this one's the b right but better than that because we have uh for free we were able to get the click event here again you can't see it but i'm gonna just click on these elements c b a all of that logic only written one time and instead of me having to write all of this all of this craziness up here three times i wrote it one time and everybody just gets the same functionality because they're all using the constructor function to be created right so hopefully the power of constructor functions is now a little more clear to you so going back to the the essence of the communication this function cuts through all the crap all the stuff that you want to do for each element every time you want to make a new instance of it all you got to do is provide the stuff that's different in this case would be the the the type and the content which is if you think about it very similar to what lisa had to do with bob or or whatever we named that guy look at that face still creepy still creeps me out but the constructor function paradigm is very similar to the communication between these two because essentially they're cutting out everything that is going to be the same for every order the only thing lisa has to communicate is the differences and again back to our function we don't have to repeat any of the steps that are shared between all the elements are similar between all the elements all i got to do when i call the constructor function is to specify the differences all right hopefully that made sense the next episode is going to be huge i'm going to dedicate the whole episode to this keyword or as i call it the original of javascript be sure to subscribe so you don't miss it this has been episode 4 of a 10 part series i'm calling 10 things javascript developers should know but probably don't thank you for joining and i will see you in the next one salute [Music] you
Info
Channel: ColorCode
Views: 44,745
Rating: undefined out of 5
Keywords: ColorCode, prototype chain, javascript inheritance and prototype chain, JavaScript, JS, ReactJS, es6, prototypal inheritance, javascript tutorial, learn javascript, javascript for beginners, coding for beginners, Javascript inheritance, javascript inheritance prototype, jS inheritance, js tutorial, Prototypal inheritance javascript, Javascript prototype, javascript objects, Web development 2021, web dev, constructor, constructors, constructor functions, web development, js 2021, jsx
Id: I37qHG0DxmE
Channel Id: undefined
Length: 17min 40sec (1060 seconds)
Published: Wed Apr 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.