For anyone confused, `this` in functions is different depending on execution context. So if you call it from the global scope aka window, this is going to equal window. Also do note that when you bind the functions with .bind or _.bind you cannot override it anymore.
Holly crap dude. This video started playing on its own after another I was watching and I'm glad my hands were busy and I didn't turn it off right away.. You have By FAR the most awesome and intuitive way of explaining things on youtube. Despite knowing all this, I still learned a lot!
After a really hard day of almost crying after work for writing as much sub-par code as I can physically type in 10 hours without a f-ing brake, you sir, have the ability to make me enthousiasthic about code again. Thank you...
I would like to add a few things that helped me personally to come to understanding (please correct me if they are wrong): - 'this' keyword refers to the , so the context is represented by an object - depends on where the function is being called from How the is determined upon function call? - dog.talk() -> the context is the left part of the call (the object within which it's being called) - talkFunction() -> here since the left part is empty, the is the global object let boundFunction = someFunction.bind(newContextObject) Here, the bind() call returns a function with artificially bound to a new object To illustrate the artificial nature of this binding, V8 debugger adds a few internal properties for a newly created bound function that can be examined in your favorite debugger such as : [[BoundArgs]], [[BoundThis]] and [[TargetFunction]] So, what essentially clarified the thing to me is realizing that 'context' is just an object which is determined upon a function call by some set of rules, and 'this' keyword simply refers to that object.
But this isn't necessarily true. As we learned a couple of weeks ago: JS is the legitimate son of Rhaegar Targaryen and Lyanna Stark, and thus not a bastard.
Interestingly enough you can fetch the talk function from the dog and bind it to a completely different object context, with a different sound: let growl = dog.talk.bind({ sound: 'growl' }); console.log(growl());
There's a looong intro and a lot of adjacent stuff before he gets to explaining how 'bind' and 'this' actually work. However, after I've watched 3 videos and read a few articles on the topic, I can wholeheartedly say that THIS is the best video I've seen. The only one that actually got me to understanding this concept. Good job! Subscribed!
Hey MP! I've only reached half way through this video and I cant tell you how satisfied I am at last by the explanations given by you on the nature of JavaScript in a nutshell. Ive gone through a ton of videos to understand how exactly the 'this' keyword works, and your video just cleared it out for me Please keep up the good work and cheers to your great presentation style, it always manages to make me smile every now and then!
7MD is all I need to watch a video. That being said, came for the video, stayed for the music, and will surely embark on the entire series, very good content!
well, I'd say the best topic for the next video is the 'prototype' keyword and inheritance. after that, some talk on class design (via the 'class' keyword) would be awesome. thx for an awesome video!
This guy... This knowledge... This ACCENT... I'm brazilian, and this accent is so beautiful to me. His teaching is excellent. Hope he returns, some day.
I only wish I could give this video more likes! I've been programming in Java for a while but find myself scratching my head a lot of the time when it comes to JavaScript, so I really love how your videos are quite informative and entertaining :D
A couple of topic suggestions for you: 1) Whilst discussing context (this) of the bind function is it worth mentioning the apply and call methods to re-enforce understanding? 2) Possibly discuss the prototype property and the pros and cons of using it - inheritance.
Very nice explanation. Next topic I hope to see: when to use bind vs call/apply. Also, the pro vs cons of the different ways of creating objects/classes in JavaScript.
Brilliant job of making things clear and simple (and humorous)! I have been using jQuery for 10+ years now, but find that I have a really hard time grasping certain JS concepts. I have to come back to them over and over and over (and over(x10)) before I get them. These videos have been really helpful in getting there. Thanks for taking the time to put them out.
WTF-SA!!! I'm so happy I searched for understanding about the Javascript bind method. Your personality and explanations are fantastic.
8 лет назад
Super cool Mattias, as always. Just one thing, in your example addEventListener() will bind this to element not to window. Glad that you started this series, I know already it's going to be great one!
I think call/apply and the way we'll often see "self" used. I recognize that you're not endorsing any of these things, but we do run across them even when we don't write them, so it's probably good that we understand them. Another good option along these lines might be "new" and the object prototype. Love your videos!
Really good. I've been programming using JavaScript for a while without knowing some of the underlying principals. I just copy/use what I know works. It's time to learn the underlying concepts
"Will output 'undefined'...when you first run across this you might be thinking 'What the fuck shit ass'... " That right there just earned you a subscription. Now I'm really looking forward to the series.
@11:41 When the realization hits that you might actually understand the concepts, and that the confusion is not eternal, it is almost orgasmic. Thank you my man. PS : If by any chance (especially because I'm finding JS confusing as heck, coming from an Java background), there is something in this playlist that is deprecated, or redundant now, please let me know. After hours of confusion, when i finally understand something, if it turns out to be futile, it would utterly destroy me. Thank you.
I was actually dealing with this quirk in a project at work recently; good to know what went wrong and how I can fix it. Thanks so much MPJ; you seriously know how to make learning the in's and out's of javascript fun!
Thanks for the awesome content, as always! One thing that I'm very confused and is kind difficult to find good resources is about promises in JavaScript.
Thanks so much for this, it clears up so many headaches for me. Having 'this' depend on how something is called was pretty confusing for me. Understanding bind will help fix many issues I've been having in my program.
To have a more functional approach you could also mention that bind can be used for partial applications. const add = (a, b) => a + b const add2 = add.bind(null, 2) add2(3) //
I want to thank you for these videos. You're very entertaining and present the material in a way that is both engaging and informative. I'm learning a lot and for that I'm very thankful. Keep it up!
Hey, I really enjoy your episodes of JS. What I would like to see next is a demonstration of how you code on a daily basis. For example, what is your preferred way of writing your scripts and what type of functions you use depending on the purpose. Something like a simple website with JS, HTML and CSS. Sometimes I get kind of lost on how to apply JS as I'm still learning. Keep your videos coming, I'm really interested!.
I'd love to see a video on object oriented programming vs functional programming, the essence, where they came from and what we have now, I think other people will find this interesting too! Thank you for your videos
Still one of my top 5 humans on earth. I remember watching MPJ 5 years ago at these videos even though I wasn’t actively learning, I just liked his personality.
The brown-nosing first, I really like your presentation style. Now to business, I would like a video on object creation around prototype. When to and not to update it.
In this line of code : btnTalk.addEventListener('click',dog.talk); 'this' would be the input's context not the window context. However in this line of code : btnTalk.addEventListener('click',dog.talk.bind(this)); 'this' here will be the window context.
Hey Mpj, I absolutely love the way you teach! This is far-fetched but would you mind doing a series on Data Structures and Algorithms? Or if not, discuss what we can do so that we could learn 'programming' not just 'programming languages'. Big big thanks!
I was with you most of the way, where I assumed you had to use bind() because you had assigned the talk function and were using it directly outside of it's context of 'dog'. That made sense. But then your real-world example caused my assumption to crumple because you referenced dog.talk() directly (so different to your contrived example) but still need bind() for talk() to know anything about the dog, in which it exists and is called on. You've left me more confused.
Your assumtion is correct, we need to use bind because we are using it outside of the context of code. The real world example is EXACTLY the same as the first one, just a different way of showing it. Can you please clarify your question/confusion a bit, and I'll try to shed light on things.
Thanks for the reply mpj! In your first example, you first assign the function to a new variable (let talkFunction=dog.talk), thus taking it out of context from the object it was defined on - so when invoked by referencing the talkFunction variable, there is no "dog" object so "this" is meaningless in that context - I get this completely. But in your Click method example you invoke the function directly on the dog object (you reference dog.talk directly in the AddEventListener method), without taking it "out of context" first. That's where I was a bit confused. I had assumed (obviously incorrectly) that invoking the method *from* the object on which it's defined should retain its "this" reference to its own object. But even though you are calling an object's method directly by referencing it through the object it is defined on, you still have to use bind() and pass it the same object again to point its "this" reference to the right object. that's what seemed a little bit bizarre to me. But if that's how Javascript rolls, then so be it! Thanks for the entertaining and informative videos :D
"But in your Click method example you invoke the function directly on the dog object (you reference dog.talk directly in the AddEventListener method), without taking it "out of context" first." I take it just as much out of context in both cases. I'm passing it as an argument into a function. Passing it to a variable does nothing different from passing the function as an argument into another function. Note that we're not invoking the function when we're passing it into addEventListener, we're passing it in, so it's just like when we're assigning it into the variable. Think about what happens inside addEventListener, that might make it easier - addEventListener just gets a function as an argument - it can only call it, it has no concept of a dog anywhere.
I.e. you assumtion " I had assumed (obviously incorrectly) that invoking the method from the object on which it's defined should retain its "this" reference to its own object." is still correct, but we're not doing that!
button.addEventListener('click', dog.talk) is the same thing as button.addEventListener('click', function() { console.log(this.sound) }) The first example copies a reference to the 'talk' function inside 'dog', in isolation, with no regard to the context in which it was defined (in the dog object)
In my mind. JS objects and bind are much easier to understand when I realize that I need to pretend to be the compiler. Most of my coding is C++ and done in Visual Studio. And the compiler parses all of my code (including things in the pre-pass section). So whenever I create JS object's, I pretend that I am the VS compiler. And I need to parse the code myself, and connect the objects to the other functions later on in the code using bind myself. In JS I am not just the code writer. I'm also the compiler. This is of course not 100% accurate. But it helps me to grasp the "this" & "bind" concepts easier.
It feels like going backwards when I see a video teaching OOP. I was very happy when you were delving into functional programming in JS. When you started with Haskell I finally subscribed. I had almost thought you might even get into Elm or PureScript and really swallow the purely functional medicine. Then you drop this video...
Please don't take this video the wrong way. I think that we should all be more functional, but you cannot be a good JavaScript programmer (and therefore not a good functional JavaScript programmer) without understanding how the language works. If for no other reason, you need to be able to read and understand object oriented code that is written by others.
Also, in order to preach functional programming, I need to attract an audience that aren't already convinced about the benefits. I don't want this channel to be a another functional bubble.
Both are great points you make, and they re-oriented my perspective on your goals for this channel. I came to your channel incidentally by looking for information on Haskell to JS transpilers. Your "Functional Programming in JavaScript" series was linked in the sidebar to some video I was watching on GHCJS. I try not to write JS directly to the greatest possible extent, but your functional JS videos were a fun diversion into how JS can be naively functional with a little effort. So early on my main interest was coming from the purely functional perspective. I do very much hope after you round out all the JS basics for your core audience that you steer back into the functional world, and I especially hope that you continue pressing on with Haskell. I think if you do, once you have the epiphany of what Haskell is and does and you get your head around basic category theory and writing side effect free programs (plus the IO monad et. al...a favorite quote of mine about side effects in Haskell is "Of all the imperative programming languages out there in the world, my favorite is the IO monad.") then I think you're going to get very excited about tools like GHCJS/PureScript/Elm/etc. And then in 2 years WebAssembly will be here and we'll be having an entirely different conversation. :D cheers and have a great week MPJ.
Keep the feedback coming, it's good to know how people feel. Don't worry, there will be plenty of nudges towards functional programming in this series. If you didn't notice it, there are plenty of hooks in this video to get people on the functional train.
I still plan to continue the Haskell series, but to set expectations - please do understand what I'm hunting for - my core value is in making programming more accessible for more types of people. Basically, I'm interested in programming languages that people that absolutely hate math can learn to love. That is why I'm so interested in JavaScript - it's a language that hits a fantastic sweet spot between power and learnability. I don't for a second think that WebAssembly will change the discussion, because I don't think JavaScript relies on browsers for it's popularity - I think it's popular because it's genuinely very effective at performing tasks that people want to do. I am a fan of functional programming, but I'm a fan because I see a lot of potential in their simplicity of making programming more accessible if we play it right. Excel is (kind of) a purely functional language that I'm pretty sure would be the world's most popular programming language if we counted it as such. Unfortunately, the functional programming community has it's head up their ass completely and has forgotten about inclusion and learning, making the languages utterly inaccessible. While the communities of OOP and procedural programming develop playgrounds for kids, teaching them the principles in early age, the functional community just seems to delve deeper into themselves. The React community is a notable exception, that ironically grew out of a PHP company. :) Either way, FP is great, but WebAssembly is not it's saviour, it needs to save itself first.
You said that "this" would reffer to the Window Object when it was inside the eventHandler. But isn't this incorrect? From what I know when "this" is used inside addEventListener it reffers to the elment that fired the event? while in the old way of doing it with attatchEvent "this" reffered to the window object and undefined under strict mode?
I was thinking the same about addEventListener. And to confirm, from MDN, "When attaching a handler function to an element using addEventListener(), the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler."