bind and this - Object Creation in JavaScript P1 - FunFunFunction #43

Поділитися
Вставка
  • Опубліковано 3 жов 2024

КОМЕНТАРІ • 663

  • @AngusMcIntyre
    @AngusMcIntyre 7 років тому +56

    "Confusion is your friend. It means you're learning" - that is going on my wall.

  • @jeffontwo8636
    @jeffontwo8636 8 років тому +39

    Best explanation of `bind` I've seen. Thanks!

  • @luxploded
    @luxploded 7 років тому +76

    *Today I learnt:* JS is a bastard from Scheme and Java.

    • @Silverjerk
      @Silverjerk 7 років тому +24

      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.

    • @romulloqueiroz
      @romulloqueiroz 5 років тому

      @@Silverjerk lol

  • @moszis
    @moszis 7 років тому +9

    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!

  • @compteprivefr
    @compteprivefr 8 років тому +182

    "Python is a language that's tightly controlled by a single Dutch, middle-aged white guy." That got my subscribe.

    • @funfunfunction
      @funfunfunction  8 років тому +14

      :)

    • @lozio2460
      @lozio2460 8 років тому +1

      lol

    • @ericgilchrist
      @ericgilchrist 7 років тому +17

      Haha! And "What the fuck-shit-ass" got mine.

    • @Silverjerk
      @Silverjerk 7 років тому +5

      And "WTF Shit Ass" is what got mine.

    • @swd1758
      @swd1758 7 років тому

      Compte Prive me too! Lol

  • @piq-dg3vz
    @piq-dg3vz 8 років тому +138

    talk about: prototypal inheritance vs class extends

    • @badqual
      @badqual 8 років тому +11

      Yes Please! it will take many eposides for that

    • @svetlanapetry5747
      @svetlanapetry5747 6 років тому

      Same thing

    • @SirusStarTV
      @SirusStarTV 4 роки тому

      👆
      just syntactic sugar

  • @archibaldmelendez
    @archibaldmelendez 8 років тому +1

    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

  • @FeanaroKurufinve
    @FeanaroKurufinve 8 років тому +12

    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!

  • @mikedeakin7518
    @mikedeakin7518 8 років тому

    Venturing into Javascript from a Java background, this looks like a perfect video series for me!

  • @dfence1985
    @dfence1985 7 років тому +62

    Dude, your videos are AMAZING. Please never stop making them.

    • @dan110024
      @dan110024 2 роки тому +5

      I think he stopped :'(

    • @MA-ek1xl
      @MA-ek1xl 2 роки тому

      @@dan110024 thank god. this video was terrible. I could barely get through it

    • @cannabisanomaly
      @cannabisanomaly Рік тому

      @@MA-ek1xl you're a doodoo head

  • @fulleride05
    @fulleride05 7 років тому

    "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.

  • @jeis93
    @jeis93 8 років тому

    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!

  • @goranudosic8420
    @goranudosic8420 8 років тому +12

    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.

  • @tapashdutta199
    @tapashdutta199 7 років тому

    U are simply an amazing person......u made my day....people should learn from u...how to enjoy while coding...

  • @roquefore
    @roquefore 6 років тому +1

    Omg, i love dat feeling when you come from "wtf shit ass" to understanding of how that stuff works!
    Amazing! Thx a lot!

  • @sachindraragul1094
    @sachindraragul1094 2 роки тому

    A simple yet clear explanation.

  • @michaelangelov5533
    @michaelangelov5533 8 років тому +6

    I suggest to describe the currying arguments using bind

  • @denisecarpenter9365
    @denisecarpenter9365 8 років тому

    Wide eyed !!! Truly enjoying you !!! I might need to go grab another glass to keep up.

  • @gilmoretj
    @gilmoretj 8 років тому

    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.

  • @SteveGriffith-Prof3ssorSt3v3
    @SteveGriffith-Prof3ssorSt3v3 8 років тому

    More video idea suggestions:
    1. Map, WeakMap, Set, WeakSet
    2. fetch and CORS

    • @CameronChardukian
      @CameronChardukian 5 років тому

      Now you're good enough to make all of these on your own! :D

  • @aleenaselegy
    @aleenaselegy 7 років тому

    different ways of object creation and their real world use-cases and their benefits and pitfalls. Nice video.

  • @anonmousse
    @anonmousse 7 років тому

    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!

  • @MapMavericks
    @MapMavericks 2 роки тому

    rewatching. Loving it, again.

  • @LautaroArino
    @LautaroArino 8 років тому

    Its going to take some more iterations for me to get to the point where i use it intuitively but you, sir, are a fantastic teacher. Thank you!

  • @darz_k.
    @darz_k. 4 роки тому

    This is brilliant - I learned JavaScript stuff and also life tips for psychologically dealing with others.

  • @milanm9907
    @milanm9907 5 років тому

    the last example helped me understand a bit more. thanks!

  • @sasirekhamsvl9504
    @sasirekhamsvl9504 4 роки тому

    I just got amazed by his entrance and subscribed 🤩

  • @oskar-hane
    @oskar-hane 8 років тому

    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) //

  • @ryanscoville3586
    @ryanscoville3586 3 роки тому

    Keep up the good work! I learn so much from your videos!!!

  • @victorejiofor8115
    @victorejiofor8115 3 роки тому

    Thanks for explaining the "BIND" method

  • @sirapatnaranong486
    @sirapatnaranong486 6 років тому

    Thanks! Well explained. I was in trouble understanding with 'this' and 'bind'.

  • @gauiis
    @gauiis 8 років тому +16

    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());

  • @lpaulger
    @lpaulger 8 років тому

    I'd like to see the different object creation methods, and what are the differences between them. I'd like to understand the cases in which they make sense, or if there *really* is no difference.

  • @Sttuey
    @Sttuey 8 років тому +8

    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.

    • @funfunfunction
      @funfunfunction  8 років тому

      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.

    • @Sttuey
      @Sttuey 8 років тому

      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

    • @funfunfunction
      @funfunfunction  8 років тому +18

      "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.

    • @funfunfunction
      @funfunfunction  8 років тому

      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!

    • @snwyowl
      @snwyowl 8 років тому +10

      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)

  • @bitphr3ak
    @bitphr3ak 8 років тому +2

    Friends: people you know, but you like them anyway...
    JavaScript: a language you know, but you like it regardless of that

  • @JesseBaker121
    @JesseBaker121 8 років тому

    Woo, part of my Monday routine fulfilled,

  • @johangudmundsson9221
    @johangudmundsson9221 8 років тому +8

    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?

    • @brocknoah
      @brocknoah 8 років тому +2

      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."

    • @funfunfunction
      @funfunfunction  8 років тому +12

      +Johan Gudmundsson you are right, I'm incorrect there.

    • @johangudmundsson9221
      @johangudmundsson9221 8 років тому +4

      Thanks for the correction MPJ!

    • @teamsteam8698
      @teamsteam8698 6 років тому +1

      That makes sense, thanks for pointing it out!

  • @MdAzharUddinresponsivelayout
    @MdAzharUddinresponsivelayout 5 років тому

    I would like to appreciate you for nice background , bright light , and sound awesome.

  • @scavadir5372
    @scavadir5372 8 років тому +5

    Great episode as usual. I'd love to see your approach to private members in JS.

  • @pollafattah7062
    @pollafattah7062 5 років тому +1

    6:20 "But let me fix that for you" :D :D I am dying

  • @mikkqu
    @mikkqu 6 років тому +2

    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.

  • @evolutionxbox
    @evolutionxbox 8 років тому +1

    Can you also talk about class free JS objects? And duck-typing?

  • @alphaomegainc
    @alphaomegainc 8 років тому +3

    an idea for the next video extending prototype vs. object literal

  • @user-zd1hj2lv3n
    @user-zd1hj2lv3n 6 років тому

    Wish everyone made learning this this fun

  • @AutisticThinker
    @AutisticThinker 6 років тому +6

    "It's installed on god damn everything" -- Love that line

  • @meerestiyak9483
    @meerestiyak9483 3 роки тому +1

    We miss you Guru 💛

  • @niclaflamme666
    @niclaflamme666 8 років тому +2

    "When you first come accross this, you're probably thinking something in the lines of .... what the fuck shit ass'
    I burst into laughter

  • @SaidElnaffar
    @SaidElnaffar 3 роки тому

    Finally, I got it -- Thanks, sir!

  • @tripfromreality
    @tripfromreality 8 років тому +1

    it would be cool with an episode about call!

  • @Buc82
    @Buc82 4 роки тому

    11:32 - "There is no this". It refers to Window (because it's the final object in the chain of prototypes) and it returns undefined because Window has no talk() method.

  • @onymalle825
    @onymalle825 4 роки тому

    good job in explaining the mysterious this keyword.

  • @justvashu
    @justvashu 8 років тому +10

    Es6 class object creation please.

  • @shvlv_music
    @shvlv_music 7 років тому

    Hi mate, u make really cool videos. Your channel was a great opening for me personally.
    By the way, I have two questions:
    1. Would you like to tell your kids (read - us) about rxjs, redux-observable, react and that part of js world?
    2. Do you use any nootropics or similar things to keep your mind so alive and productive? As I understand, you work all the week and spend one weekend day for FFF. Applying this to me, I will become deadly tired in one month of such tight schedule.
    Thanks,
    John

  • @techit_ezy
    @techit_ezy 7 років тому

    AWESOMEEE!! *drums rolling

  • @Ritchie_The_CEO
    @Ritchie_The_CEO 7 років тому +7

    wtfsa
    A t-shirt waiting to be made!

  •  8 років тому

    I next episodes I would like to see some explanation of super() that makes me super confused in ES6 Classes. It makes me confused because I don't have experience with other programming languages - js is my thing.
    Another cool thing to see would be episode about patterns in OO js. How to create a plugin that does some DOM magic, should I for Class, constructor function, new keyword, Object.create() etc...

  • @rickmedina4082
    @rickmedina4082 8 років тому +6

    A video about testing in JS please!

  • @JonathanDupre
    @JonathanDupre 8 років тому +4

    ua-cam.com/video/GhbhD1HR5vk/v-deo.htmlm25s
    I really thought you were going to say: "let the dogs out"

  • @nicolebanta7315
    @nicolebanta7315 4 роки тому

    this was a beautiful explanation! Thank you!

  • @ivofs
    @ivofs 8 років тому

    Thanks +funfunfunction ! Great videa!
    It seems to me that we should understand better how to modularize our JS code with some real life examples. I vote for a why/what/how video about modules.
    Thanks

  • @zhenwang7380
    @zhenwang7380 5 років тому

    11:24 really great explanation!!!

  • @cdential3561
    @cdential3561 3 роки тому

    Loved it! Resolved the mystery :D

  • @SouravBanik90
    @SouravBanik90 3 роки тому +1

    For the first time in 7-8years of working with jquery, I finally understand bind! Thank you!

  • @bw7891
    @bw7891 4 роки тому

    fun and interesting, and best explanation !

  • @DaveDuran
    @DaveDuran 7 років тому +4

    WARNING: At around 6:55 I was taking a drink of coffee and spit all over my keyboard. :)

  • @NckNck-pu9vb
    @NckNck-pu9vb 8 років тому

    These videos are awesome.

  • @leoking938
    @leoking938 8 років тому

    Like some people have mentioned here, I would prefer more functional programming videos, like the Haskell series. I love this OO type of videos too, so either one is fine really. Just letting you know that don't forget completely about the Functional Programming series :]

  • @EricBaileyDrums
    @EricBaileyDrums 8 років тому

    Hey MPJ, what do you think of using this way?
    let dog = new function() {
    const sound = "woof";
    this.bark = function() {
    console.log(sound);
    }
    };
    let barkFunction = dog.bark;
    barkFunction(); // this logs "woof" as expected

  • @promisetochi
    @promisetochi 8 років тому +1

    If you use 'this' in a global function, in ecma3 and ecma5 sloppy mode, i think it will be bound to the window object in browsers, and if you have a global variable 'sound', i think you will get an output, albeit a crazy one.
    I want to see how to apply functional principles in design patterns. or just talk about design patterns and projects newbies can do to master design patterns, also i want you to talk about the usefulness of coding challenges, that usually involve complex maths, like those on projecteuler.net, they seem pretty useless, do i need to be able to solve them as a programmer, do you solve them and do they make one a better programmer?
    The compose(funcA(), funcB()) function of functional programming will also make a good topic.
    A quick question: Is it possible to use only pure functions throughout a small project like a simple html,css,javascript calculator?

  • @thedoortonowhere
    @thedoortonowhere 8 років тому +1

    Hey, I have an idea. One of the things that I have difficulty with is figuring out what random "this"es in code are referring to. These are statements inside functions that are not in a particular object and not referring to some data defined right next to them like the clean example in this video. I'm not sure if there are any good tricks aside from painstakingly backtracking to figure out what a particular "this" refers to, but it's been a pain point for me since I started working with JS.
    A "this" that isn't referring to its immediate parent just seems too vague to me, like I can read all the code around it but I can't read the "this". It has no meaning that I can interpret, so I have to guess based on context. When the rest of JS reads so clearly to me, this feels weird, like I'm missing something.

  • @daniellaerachannel
    @daniellaerachannel 6 років тому

    at 12:00 finally got the f***ing meaning of this. thaanks

  • @mubashirwaheed474
    @mubashirwaheed474 3 роки тому

    thank you so much for making this video

  • @reveryoungfo
    @reveryoungfo 6 років тому

    To be short:
    when the function is treated as method the 'this' is going to point at object
    but
    when function is just function (not method) e.x. you assign method to string, 'this' is going to point at parent of 'standing alone' function
    We use bind(object) to say that function is a method of that object.
    Am I right?

    • @funfunfunction
      @funfunfunction  6 років тому +1

      No, I think you need to let go of the method/parent semantics from your mind. Those do not exist in JavaScript.

  • @jonathansilva3364
    @jonathansilva3364 8 років тому +3

    Hey, what about Prototype for the next video? I think it would be nice!!

  • @arpielen
    @arpielen 3 роки тому +1

    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.

  • @benjonyc
    @benjonyc 8 років тому +1

    In node I see this defined as self (a lot) and in Angular apps I see objects also caching the this keyword as self etc. Why are most developers reassigning/caching the this keyword instead of using bind? It is just an oversight or a style choice?

  • @surajshetke4440
    @surajshetke4440 3 роки тому

    Ek Number Full Clear . Of bind

  • @Martin-4D
    @Martin-4D 6 років тому

    Awesome channel. Thanks dude

  • @hashankarunathilaka4229
    @hashankarunathilaka4229 5 років тому

    Great content brother

  • @stevenliemberg
    @stevenliemberg 8 років тому +1

    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...

  • @anubhavsingh2916
    @anubhavsingh2916 2 роки тому

    you explained very well

  • @Will-tb8qm
    @Will-tb8qm 7 років тому +1

    this.sound, not this, is undefined in talkFunction. In talkFunction, this is the global object.

  • @cavalcantegb
    @cavalcantegb 7 років тому +3

    Thanks for the video! I've been struggling to learn JavaScript lately, but your content is helping me a lot!

  • @alvarobelusi
    @alvarobelusi 8 років тому

    Cool video. Congratulations!

  • @compeng2013
    @compeng2013 7 років тому +9

    Rofl. Just died @6:56

    • @grayrachelle
      @grayrachelle 7 років тому

      @6:49: guffaws. I like the expressions even more than the swearing lol

  • @MrFliperocha
    @MrFliperocha 6 років тому +1

    Nice job!

  • @NoobieDoobieDo
    @NoobieDoobieDo 8 років тому

    Please normalize the volume of future videos if you have not already. Great videos. Thanks

  • @ruxandraanghel9854
    @ruxandraanghel9854 7 років тому +1

    Hye MPJ, thank you for the videos. They're amazing! Kudos to your aggressive approach XD.

  • @ItsMeShaad
    @ItsMeShaad 8 років тому +1

    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.

  • @psnull.
    @psnull. 8 років тому

    omfg this is just what i wanted
    mpj are you a wizard

  • @emilios1995
    @emilios1995 8 років тому +1

    Good episode! I'd like one about ways to do mixins in js.

  • @TomWatches
    @TomWatches 8 років тому +1

    Hey very nice video, as always.
    It would be fun to see a video about all the quirks of javascript or things where people would scratch their heads. I'm thinking of a video similar to: www.destroyallsoftware.com/talks/wat @ minute 1:30. I laughed hard and searched for more such things. Would like to see you making something similar one day :).

    • @blueplane1
      @blueplane1 8 років тому

      Thanks for posting that link. That was a good watch.

  • @JohnBehan
    @JohnBehan 8 років тому +1

    "What the fuck shit ass" says me at least twice a day (let me = this)

  • @aliciarojas8604
    @aliciarojas8604 3 роки тому

    This is still useful in 2021 :)

  • @ArjunSingh-oo1mh
    @ArjunSingh-oo1mh 6 років тому

    Can you please give a live example by executing it either on browser or some other compiler.

  • @wahibakamoulcode
    @wahibakamoulcode 6 років тому

    // I used this code with an arrow function, and when I call this function it gives me undefined not the value of the sound property thanks
    let dog = {
    sound: 'haaw haaaw haw',
    talk: () => console.log(this.sound)
    }
    dog.talk() // undefined !!!

  • @fhdhsni
    @fhdhsni 8 років тому

    In arrow function episode you said `this` acts this different in arrow functions. I'd like to know how it's different. thank you.

  • @DanielGonzalez-ij4yq
    @DanielGonzalez-ij4yq 7 років тому +2

    6:51 pretty much describes my entire web developer career

  • @true_podejrzany
    @true_podejrzany 7 років тому

    Im curious what exactly bind does that makes "this" keyword behave like it was in context of object that was passed in as an argument. Does method keep it as some kind of closure and relates to it?

  • @LeeHongYee99
    @LeeHongYee99 6 років тому

    Bind is to let a function switch its “this” ref to another object