Javascript Context Tutorial - What makes Javascript Weird...and Awesome Pt5
Skills:
JavaScript Fundamentals90%
Key Takeaways
Understanding JavaScript context using Call, Apply, and Bind methods
Full Transcript
okay everybody I need you to take a deep breath in okay we are about to cover context which is easily one of the most complicated Concepts to grasp with JavaScript it's not actually a difficult concept uh when you get it it makes sense uh but grasping it and grasping how it applies can be very difficult for JavaScript developers especially if you're starting off so I'm going to try to get into it going to try to make it as easy as possible but don't feel bad if you to rewatch this video multiple times it's just not that easy to get the first time around once again context is the is what the value of this is for your code that is running um I'll just let the code do the talking here let's go ahead and get this console log nice and big here um if I was to console log the value of this in my root scope by default this is the window object so if I was to console log does this equal window yes this equals window so I could actually go ver a equals 1 and console log this. a and it equals 1 I have no reason to do that in when I'm working in the root scope I could go window. a equals 1 I could also just go console log a that also equals one uh but that just shows you in the default the root scope the context is this um I could also go function Fu con log this and then let's run Fu and you'll see that that's also the window object if you remember from the scope video the scope has changed we now have a child scope but the context is still this now the reason why is because by default a a function runs within the scope of the object that it sits in so I can also run it as window Fu CU if you remember when you create something in the root scope it's a part of the window object whenever I run FU by default it's going to run within the context of the object that it sits on that's why window is the default uh context let me show you how that context can be different if I go ver OBS let's create an object now and let's create a method or a function on this fu is a function and this will just console log this so now I'm going to run ob. fu and now it's console logging the object as the value of this it's running OB I could also say does this equal obge yes true does this equal window no false by default and I keep saying by default uh by default it runs with a context of the this value is the object that that sits on now one of the tricky things about context is that this value can actually change depending on how how you call this Fu function depending on who runs it and by and how they're running it uh the value of this can actually change and at first that sounds stupid why would you want the exact same code for all the values to be different uh but the next example I'll show you uh shows you exactly why that's very useful real quick I'll show you the three JavaScript methods of changing context they are call apply and bind I won't go too deep into this but it's just important that you know these are the three do that um so basically I can go call Fu call window and now it's going to run object. Fu but it's going to change the context to window so now does this equal window yes it does if I take that away and just run Foo does this equal window no it does not so what I've done with call is I've changed the context that this fires in and the next uh if you give call more than one argument uh say 1 2 3 then that's the arguments that you're passing up here so basically if I give it one one's going to go up there two's going to go up there three is going to go up there if I need to pass arguments to the function so you just go on and on and on with call call and apply are basically the exact same thing the only difference is is apply only takes two arguments it takes the new context and it takes an array which are going to be all the arguments up here so I give it an array and now the first of the array goes there the second of the array goes there and the third of the array goes there so call and apply are the exact same thing bind is a little different takes the one argument and what it does is it doesn't actually execute your Fu function like call and apply do it returns a bound function so I could go bear my bound Fu equals this and so now my bound fu is a function that always executes Foo with the context of window so now every time I run my bound Foo it will console log this equals window true so if I run my bound Fu true if I go obj Fu then it's going to say false so true when I run it here the context is window false when I run it normally the context is not window it's OB so that's kind of how you change it probably doesn't make sense as to why you need to change it uh all that need all that you need to know is that it can be changed let me let me show you now how uh an actual real world example of that being a different value uh let's go jQuery here body onclick function i instead of doing a function I'll just go obj Fu so now I'm going to run ob. Fu when the body is clicked so there you go and it says that the context is not window when I run Fu let me see what is the context click on the body and the context is the element that was clicked on uh with JavaScript Whenever you set up an event listener on the click element when I set up a click listener on the body element um and I run that then it's going to run with the context of the element that was clicked that way I have access to it so now whenever I run this I know which element was clicked by the this op object this points to the body element in the Dom so let me show you how this is actually useful um down here I have an Li let me show you the code I have UL with Lis in it each Li has been clicked zero times and we want to increment this when you click on the LI pretty simple so I'm going to go Li on click function and now I'm going to go let's uh so right now whenever I click on An Li what I've done is I have set up an Li listener so this listener is on all liis and whenever I click on it um the this function the this value will not be all liis the this value will only be the element that was clicked so there we go I click and the first time you can see that it's that Li if I were to click this Li now the this is the third Li if I if I click here this is the second Li so what I can do is I can go Li span HTML um so let me I'm going to actually go there current times I'm going to grab the number of times it's been clicked I actually have to parse it as an integer CU by default in the HTML that zero is a zero string it's not a zero number so I have to parse it I have to get the HTML of that span parse it into a number and then I'm going to go Li I span again is going to be current times + one so if I do this it's going to change all Li spans that's not the desired effect I want to only change the LI that got clicked on so now I can actually use this this points to the LI that got the click let's find a span inside of that Li which is where find is very useful and let's get that HTML so I'm getting the value when you click on this Li it's going to find a span inside it's going to grab that HTML value out of it parse it into an integer and now same thing right here and so then same thing I want to find that same span and I want to print the new incremented value in there so that will now only change the one I clicked on only change the one I clicked on only only Chang the one I clicked on let me give you a common problem that people run into now that has to do with context uh let's go on to my second example code my second example code here is I've got a div with a bunch of nasty HTML that I printed in line I printed some Styles in line which of course is a terrible id idea um this div is hidden it's got a display none on it um and so I want to show that div um let's save that there we go and so now what I'm going to do is on I think that's called open div that's what this button is called open div on click I'm going to I'm going to do two things here the first thing I'm going to do is I'm going to grab this which is the button that got the click open div and I'm going to toggle the class to active there you go so there you go the class active is going to toggle off and on um so then what I want to do is I want to find what's the name of that div oh div one I'm now going to find div 1 and I'm going to slide toggle that there we go let's say some guy in the business department said absolutely I cannot toggle this class to Green until it slid out let's say there's something more going on here there's 10 different animations and I had to wait until it had sliden down to toggle this to Green so then what I have to do is I have to slide it to toggle and I have to run a call back and then after it slid then this call back functional fire and then I'm going to toggle this to active there we go save the code run it slides out fine but it doesn't toggle to active why doesn't that toggle to active because this is now pointing to div one this is a call back to this event listener and it's no longer firing in context to open div it's kind of like remember when we had that scope naming conflict if I do ver a equals 1 here and ver a equals 2 here I've now created a name conflict now I have no way of accessing this a um that just happened with this that just happened with my context um when this thing calls this it's going to look and see that my fun function already has a context that context is div one so I have no way of accessing at this uh there's there's two ways to get around it you can get around it uh with scope I do have access since this was this function was created in this scope here I have access to all the parent scope variables so I can go ver self equals this I can create a variable that variable all it does is point to this and now I have access to self if I look for self it's going to look in this context okay self has not been created let's look in my parent scope ah self has been created it points to this which is the open div and now it's going to work there you go um You can call this anything you want some people call it underscore self some people call it underscore this uh some people will call it open div uh you can really call it whatever you want as long as it makes sense uh but that's kind of how you get around it using scoping creating a parent scope variable that you have access to uh the other way around it is you can actually bind this function right here to always run within the context of this so what you can do is when I create this function I can go bind this so that it creates the function it runs bind on the function and it returns that bound function to the second argument of slide toggle so now in this inside of this call back this will always equal open div so that will also work this that that this this that hopefully you're not too confused by that so that's the way you can do it with bind only disadvantage to using bind is it's a lot less code um but I have no way of accessing this as div one anymore because it has been bound to where this always equals open div uh you may have to watch this part again to really get what just happened but that's kind of your intro to context I'm going to create one more video on context where we get into the JavaScript modular pattern it's kind of something you want to know before you start learning backbone.js uh but let's go ahead and close this up for now that's context that's the weird and cool things about JavaScript hope you enjoyed the lesson have a great day
Original Description
View whole series here: https://www.youtube.com/playlist?list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_
Call, Apply & Bind are avoided by many JS developers, but it doesn't have to be that way. Context is a simple concept that creates complicated realities for developers. In this javascript tutorial, we're going to cover context in javascript, how it's determined, and how/why it changes.
When you understand context, you'll feel much more at home with Javascript as a language, and callbacks, especially will feel much more familiar to you.
-~-~~-~~~-~~-~-
Also watch: "Responsive Design Tutorial - Tips for making web sites look great on any device"
https://www.youtube.com/watch?v=fgOO9YUFlGI
-~-~~-~~~-~~-~-
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from LearnCode.academy · LearnCode.academy · 42 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
▶
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Web Development Tutorial for Beginners (#1) - How to build webpages with HTML, CSS, Javascript
LearnCode.academy
Web Development Tutorial for Beginners (#2) - Basic CSS - How to build a website with HTML & CSS
LearnCode.academy
How to create CSS Layouts - Web Development Tutorial for Beginners (#3) - with HTML & CSS
LearnCode.academy
Bootstrap Tutorial For Beginners - Responsive Design with Bootstrap 3 - Responsive HTML, CSS
LearnCode.academy
Angularjs Tutorial for Beginners - learn Angular.js using UI-Router
LearnCode.academy
CSS Tutorial - Web Development Tutorial for Beginners (#5)
LearnCode.academy
Node.js tutorial for beginners - an introduction to Node.js with Express.js
LearnCode.academy
Github Tutorial For Beginners - Github Basics for Mac or Windows & Source Control Basics
LearnCode.academy
Javascript Tutorial - Programming Tutorial for Beginners Pt 1
LearnCode.academy
Javascript Tutorial - jQuery Tutorial for Beginners Pt 2
LearnCode.academy
AngularJS Directives Tutorial - Part 1 - Demystifying Angular Directives
LearnCode.academy
WATCH THIS IF YOU WANT TO BECOME A WEB DEVELOPER! - Web Development Career advice
LearnCode.academy
YEOMAN TUTORIAL - Master Front-End Workflow with Yeoman, Grunt and Bower
LearnCode.academy
BOWER! - Streamline Web Workflow with Bower Package Manager
LearnCode.academy
Chrome DevTools for CSS - Better CSS Coding & CSS Debugging with Developer Tools
LearnCode.academy
GITHUB ATOM - Why Atom.io will be your favorite Text Editor!
LearnCode.academy
GITHUB PULL REQUEST, Branching, Merging & Team Workflow
LearnCode.academy
Pimp that Terminal - Add shortcuts and functions to your .bash_profile to simplify routine tasks
LearnCode.academy
jQuery Tutorial #3 - Writing Smarter, Better Code - jQuery Tutorial for Beginners
LearnCode.academy
jQuery Tutorial #2 - Event Binding - jQuery Tutorial for Beginners
LearnCode.academy
jQuery Tutorial #1 - jQuery Tutorial for Beginners
LearnCode.academy
Node.js MongoDB Tutorial using Mongoose
LearnCode.academy
Node.js tutorial for beginners 2014 - an introduction to Node.js with Express.js
LearnCode.academy
WEB DEVELOPMENT - SECRETS TO STARTING A CAREER in the Web Development Industry
LearnCode.academy
jQuery Tutorial #4 - DOM Traversal with jQuery
LearnCode.academy
jQuery Tutorial #5 - Building a jQuery Tab Panel Widget
LearnCode.academy
jQuery Tutorial #6 - Building a jQuery Image Slider
LearnCode.academy
jQuery Ajax Tutorial #1 - Using AJAX & API's (jQuery Tutorial #7)
LearnCode.academy
jQuery Ajax Tutorial #2 - Posting data to backend (jQuery tutorial #8)
LearnCode.academy
jQuery Ajax Tutorial #3 - Delegating Events & Mustache.js Templating (jQuery tutorial #9)
LearnCode.academy
jQuery Ajax Tutorial #4 - "Edit" modes & Better Mustache.js Templating (jQuery tutorial #9)
LearnCode.academy
How to put your website online - how to FTP to a domain & upload files to a webhost
LearnCode.academy
Basic Terminal Usage - Cheat Sheet to make the command line EASY
LearnCode.academy
SSH Tutorial - Basic server administration with SSH
LearnCode.academy
Vagrant Tutorial - Running a VM For Your Local Development Environment
LearnCode.academy
Sublime Text Favorite Packages and Workflow
LearnCode.academy
What Makes Javascript Weird...and AWESOME - Pt 1
LearnCode.academy
Javascript is Event-Driven - What makes Javascript Weird...and Awesome Pt 2
LearnCode.academy
Javascript Closures Tutorial - What makes Javascript Weird...and Awesome Pt 3
LearnCode.academy
FREE REST API - Practice Developing Javascript AJAX Apps with this API
LearnCode.academy
Javascript Scope Tutorial - What Makes Javascript Weird...and Awesome Pt 4
LearnCode.academy
Javascript Context Tutorial - What makes Javascript Weird...and Awesome Pt5
LearnCode.academy
Nginx Tutorial - Proxy to Express Application, Load Balancer, Static Cache Files
LearnCode.academy
Live Reload Sublime, Chrome, Anything - Fast and easy with Live-Server
LearnCode.academy
Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators
LearnCode.academy
Javascript Generators - THEY CHANGE EVERYTHING - ES6 Generators Harmony Generators
LearnCode.academy
Web Development Advice - Interview with Dev Tips
LearnCode.academy
How the Internet Works for Developers - Pt 2 - Servers & Scaling
LearnCode.academy
How the Internet Works for Developers - Pt 1 - Overview & Frontend
LearnCode.academy
HAPROXY vs NGINX - 10,000 requests while killing servers
LearnCode.academy
Node.js Cluster - Boost Node App Performance & Stability with Clustering
LearnCode.academy
Web Dev Training with Treehouse
LearnCode.academy
What is Node.js Exactly? - a beginners introduction to Nodejs
LearnCode.academy
How to deploy node.js applications #1 - spin up a server
LearnCode.academy
Deploying node.js applications #2 - provision server & setup flightplan
LearnCode.academy
Deploying Node.js Applications - Deploy Node the right way - as an Upstart Service
LearnCode.academy
Mobile Web Design - Coding Workflow For Mobile Websites
LearnCode.academy
WHY YOU NEED A BUILD SYSTEM LIKE GRUNT, GULP, BRUNCH FOR YOUR WEBSITE
LearnCode.academy
GRUNT TUTORIAL - Grunt makes your web development better!
LearnCode.academy
STOP USING FTP! - How to Deploy with Flightplan over SSH
LearnCode.academy
More on: JavaScript Fundamentals
View skill →
🎓
Tutor Explanation
DeepCamp AI