The Importance of THIS in Javascript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there sexy sausage in the last couple of weeks I've grown a bit tired of of this whole framework War to be honest of the next people arguing and then the spelled people arguing about their own stuff and I thought to myself oh do I really want to get into it to make content about this and hear people arguing uh and I thought why not just focus on just JavaScript for a wee bit because at the end of the day all of these Frameworks they're just there's no magic behind it it's all written in JavaScript with some compiling magic going on there so I thought we'll cover the keyboard This apply column bind because they're really important topics and if we get a good understanding with it in this episode we might build a little like jQuery clone that's just gonna be a super simple example not too crazy but hope you'll understand it alright also drop a like support this channel subscribe it goes a long way and check out any of my courses at developed by ed.com okay so let's get started with the keyword this so it can be a bit difficult to explain but this is essentially a reference to an object so by default and like a global execution context so if I just wrote this anywhere in my Javascript file it's gonna mean either two things depending on which environment you're working in so if you're working in the browser the this keyword is going to refer to the window object and if I open this up and I'll show you here it's just a silly little website and you're going to see the window object and this window object holds all of the fun apis that you know and love in JavaScript like crypto if you want to generate the random ID or you have a set interval clear timeout right this is I set both of those wrong clear interval and clear timeout and then the inner width all right you know the Jazz now and if you're working with node then it's going to refer to a global object um but that's it now what we also learned is that functions have their own execution context right so if I make a function called uh get user detail or something like that all right I can have a variable here like age and that's 25 right so we learned that if if we create a function it's it also creates its own execution context and the variable is here the variables here are scoped to this function specifically so there's no way for me to do something like that that's going to error out right if this age would have been in the global execution context up here then it's accessible to anything outside and inside a function so that would break there and this would also work there so if I do a get user detail and that and then if we have a look here and then inspect we're gonna see 2525 all right but what you have to keep in mind is if we console log this in like a top level function is still gonna refer to the window object all right so if I do console log sorry not console log get user detail and hit save you're gonna see that we still have the window all right but what it's recommended to do is to add this you strict and as you can see if I had the use tricked it's gonna stop you from doing silly bugger mistakes and you're gonna get undefined because when we're talking about the keyword this we rarely want to talk about the window object if we do need the window object we just type it out right we say window so the keyword this is not really meant to be used in that way right where we're just referencing to the window object so it's always I always recommend enabling strict mode when you're working with the this keyword which has to stop you from doing these solid mistakes alright so we know that now how can let's let's draw in another example so in what context get the keyword this change well if we have an object so let's say we have a user object and here we'll have an age for example property of 25 we have a name of developed by add but here we might have a function like get details and I'll set that over to a function here like that and here I'm just going to do a console log and do back text and say my name is this the name and oops give me the backticks and my age is this dot h all right so and we say user dot get details here and have a look as you can see but this keyword now references the user and the easiest way to know whether this keyword represents when you are calling it on the method here when you have a method on an object is to see where you're invoking the function here so get details right and look to the left side of it so if we if it's a method on the user then this keyword is going to mean user all right so it's user dot name so user dot name it's going to give me develop I add now don't make this common uh error where you say const user detail and assign that to user.get details all right we're just passing reference to it but when we're invoking the function you are going to see that we get undefined all right so look where we're invoking the function take a look at your left what do you have do you have any user no then this keyword is is not going to be associated with it anymore but what if I want to make this a bit more flexible because right now yeah this works on the user here but what if I have two users you know I don't want to add a method to all of them that pretty much has the same functionality so what will we do in that case well we probably split it outside and have it up here so we could say cons sorry we can say function get details or we could just call this get user details to be a bit more clear so we can set that equal to a function here like that and I'll just copy this right so again in this context that this keyword is going to reference to the global uh object window so what we'll do is we'll remove this from here like that and hit save all right so now they are completely separate how can we combine them together because again I can go here and I might just say user or I can just call this Edwin right and then I might have another user here called Charlie right and this might have a different age have a different name all right and you might actually have maybe about me or something I like turtles all right and then here you might have another about me or like this about me description there we go I like to play with the computers there we go hit save all right so we have two objects so this is a bit more nice because we'd have to add these basically on both right because we want to do the same thing which is inefficient because we're allocating memory to both of these functions what we can do is use one of the three methods called call bind and apply so what is bind first of all bind basically lets us get the function so in this case get user details and if I add bind I'm basically binding the object that I wanted to be referenced to so if I say I want this to bind to Edwin then this keyword is gonna reference to the add one object all right so this one here so if I hit save and if we look in the browser let's have a look and do a refresh as you can see nothing's gonna happen so if I invoke the function down here you're going to see it still says undefined and yeah undefined again so why is this happening remember if you use bind it creates a new instance of a function associating it with the object so we need to save this so I can call it something like Edwin's detail so this is again a function right so rather than doing get user details we do admin detail and then invoke it like that so now if we have a look look at that my name is developed by add and my age is 25. all right but there might be cases where you don't want to create an instance of a new function and you just want to invoke it directly without taking up any memory space so that's where you can use call again with call we don't need to assign it to a new variable all right so the function is not going to be stored anywhere what we can do is just get user details call and call it with this object in mind so if we have a look as you can see now it invokes the directly without creating a reference and then we can do the same with Charlie as well so if I do Charlie here and there you go oh and if you want to pass down additional arguments you can also do that here so if I want to pass in some kind of date like 94 I can pass down maybe a hobby that I have so maybe games I have no idea uh then we can pass it in here date and then you'd have uh interests or something right so you can add that here as well so comma I'll just add a date like that just so you can see there we go and if we go back here and do a refresh as you can see we have 94. all right and there is another one called apply besides call and the only difference with that is is that these additional parameters are passed down as an array like that all right but everything else should still work the same now if we're working with classes it's pretty much the same as working with a Constructor on the function so I can if I do like a class of country like that or a class of user we can do a Constructor here and pass and maybe a name and an age all right and then here we can call the keyword this the name and set it equal to the parameter that gets passed down and then we can call this dot age and set that equal to the age as well like that and again we can have maybe a describe method down here where we can just console log and say this dot name is now a user on this website and his age is and then we can do this now h all right I hit save perfect so now if I make a new user here so I'll say user equals new user specifically with the new keyword here that's very very important because the new keyword is gonna instantiate a new object for us and when the new keywords gets used the this keyword is going to reference to the new instantiated object that we're making down here so here I can pass in the two parameters that I'm looking for so I can say developed by add and I can pass in an age like 25 and then if I call user dot describe we are gonna get the same kind of response all right now be careful when you're working with arrow functions because the arrow functions do not have their own this binding all right let me show you an example so we're gonna go back to the user here we're going to give it a name of develop by Ed and I'll have two methods here so we have a regular function that you normally make like this with the function keyword right and then here you'd say console log this dot name alright so you know that works you know that this here is going to reference to the user object however if I do an arrow function which you make by doing the parameters and then the little equals an arrow and here if you say console log this dot name you are gonna find uh very very soon that if we say user.regular function and user.arrow function you're gonna see that the second one we are not gonna get so be careful with this when you use Arrow functions it's always going to reference uh the next level up of the execution so when is this useful well there is another case where we might have this keyword so take this title for example here we have a H1 so now check this out if I go and add a title.ad event listener and let's just add a click here and I'm gonna run a normal function so if you run a normal function then the keyword this is always going to reference to the current Target so the current Target in this case is going to be the title right so you might want this you might not want this you might want to just have an arrow function here and then it's we're back to referencing the this uh the window object okay now that we have a bit of an understanding of all of these terms let's see if we can put together a small little Library that's going to animate any element that we want kind of jQuery style whether to remove all these paragraphs fade them in fade them out uh yeah so here's what we're gonna do we're gonna create a variable first I'm gonna call this like a dollar sign the name that you pick here is really depends you're going to see a lot of people do like underscores uh because you don't want to interfere with any of the other apis that are on the window object so that's why you might see dollar signs or underscore something here happening and we'll just call this dollar sign and set that equal to a function and basically what we want to do is kind of make like a jQuery selector where you can go like that and I want to select the P tags and then let's say I want to be able to like chain together different commands like add a class of uh fade or maybe fade out like that and I can pass in a time so we're going to be creating something similar to this so what do we need well we made a variable called dollar sign and we have a function here so we're going to need a selector in this function so I'll just pass in selector like that and what can our selector be well it can be either one element or it can be multiple different elements right what if the speed tag here and we have multiple of them right and I want to animate all of them out so what I can do is create an element variable here and I'll just say document.queryselector all and rather than passing in the selector like that though we could probably do that in this case what we can do is just add a call on it and I'm passing in the document and the selector here so what I'm saying basically is um always reference the document object and this is the selector that I'm passing it down to so in this case the paragraph all right cool now what we'll do is create our actual Library functionality that's misspell for sure so what we'll do is call it yeah Library and here the first thing we're going to pass it in is the actual elements that we're going to animate and the second parameter can be all of our different methods so we can maybe do an ad class that's going to take on a class name and here what I want to do is call this dot elements dot for each again if we have a look here that this keyword references the actual Library object so I'm calling basically a library the elements and for each element that we have what I want to do is say element dot class list dot add and we'll add the class name that the user wanted to add and that's it that's literally a simple line of code but we need one more thing here so after we do this um we might actually need to expand this Let's do let's go back here let's just do it like this element and I'll explain why there we go we're gonna open this up like that and say element the class list I'll add class name and at the end here what I want to do is return the library like that now why are we returning the library returning the library is going to be able to give us the ability to chain together all of these different methods essentially so I can add the add class here but then I can still let the dot Fade Out or any other class that I want to keep going and going so now what I can do if I want to go down here I can maybe add a Fade Out so let's create that as well Fade Out this is going to take a duration in and again it's going to be this dot elements for each element we are going to run a function here and what I'm gonna do is get the current opacity of this so I'm going to assume it's one uh then it's probably not a good idea actually to assume it's one but we'll just go with this uh we'll do decrement probably the best way would be to kind of go out and see what the current capacity of is and then decrement from there but we'll keep it simple for now decrement I'll take the one and divide it by duration divided by let's say 10. cool and then here we'll do a fade and I'm just going to set an interval like that and this is going to take 10 and basically what I want to do is do the current a pass at the end just like decrement it so I'm going to say minus equals to decrement but what I also want to do to make it a bit more fun is when it goes to opacity zero I want to remove it with display none so what we can do is element style the opacity is equal to the current opacity right now perfect so after this again what we'll do here at the end let's go let's see one down two down right here and say return library as well and that should kind of be it as you can see nothing's actually erroring out here anymore so let's try it on maybe this H1 so we can go down here and say dollar sign um and then as you can see we can put in a selector of course again if you want to make this really nice you'd add all the typescript support and everything to it but let's try it we'll grab the title and then on the title we can do maybe a fade out and pass it in a thousand so let's have a look who looks like we are getting an error so let's see what's up with that oh my apologies I did forget one thing here we're never clearing the interval so let's say if current opacity is smaller or equal than zero then what we want to do is just get rid of this interval and pass it down that fade and then element style display will set it to none we totally forgot to add this functionality because here we're just fading it out but when we reach zero we want to get rid of the interval and also add zero to that or display none but there is still one thing I forgot is you're gonna get this error here right now saying cannot read property of undefined so what we have to do is on this Library object at the end also return library like that cool so now let's see if we do a dollar sign and then we can pass in the selector so we can say dot title and then look at that we can pass in at class or Fade Out or we can get the elements but we're not gonna do that so let's say at class and fade let's just say fade so let's see if that works we'll select the element and look at that it has a fade awesome so we can add classes if we want and we can also actually add a fade out to it like a second then boom and look at that once it reaches zero it also adds the display none to it which is really cool will this work on multiple elements so let's give that a shot P tag save and Boop look at that display none everything works really fine so that's it hope you enjoyed this little episode here hope you learned something new I am more than happy to keep up the series because yeah it's honestly more fun uh to kind of see how the inner workings of JavaScript and also I really want to get more into typescript typescript and teaching that on the channel so let me know if you want to see more of this stuff I'm happy and excited to make it and until next time I wish you a great day and get out of here
Info
Channel: developedbyed
Views: 8,544
Rating: undefined out of 5
Keywords: javascript, javascript this, this, javascript for beginners, js library, javascript library, javascript in 20 minutes, call, apply, bind, functions, javascript functions
Id: LEw0hswTots
Channel Id: undefined
Length: 22min 59sec (1379 seconds)
Published: Sun Jul 02 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.