Examples of this and bind - Object Creation in JavaScript P2 - FunFunFunction #44

แชร์
ฝัง
  • เผยแพร่เมื่อ 17 ก.ย. 2024
  • 💖 Support the show by becoming a Patreon
    / funfunfunction
    Today, I’m going to show examples of this and bind. In the last episode we explored this and bind. Reading the comments of the last video, it’s clear that some people had an aha moment around this, but for a lot of you it this didn’t click. It really, really important that we understand the concept of this in order to learn the object model in JavaScript, so I’m going to spend a video on doing a bunch of more examples, so that more people get it.
    This video is part a series on object creation on JavaScript, that is for you if are coming from another programming language into JavaScript and you’re already somewhat familiar with object oriented programming. You know what classes and inheritance is, but you’re confused about how object orientation is done in JavaScript. You’ll get much more out of this video if you watch this series from the the start - you can find a link the full series in the episode description.
    Table of contents:
    02:19 ► What is this in JavaScript
    04:16 ► Bind in JavaScript
    06:29 ► Functions as properties on objects
    07:00 ► Functions are values in JavaScript
    Resources:
    Object creation in JavaScript - Complete series playlist
    goo.gl/RaBJDo
    💛 Follow on Twitch and support by becoming a Subscriber
    We record the show live Mondays 7 AM PT
    / funfunfunction
    💛 Fun Fun Forum
    Private discussion forum with other viewers in between shows. www.funfunforu.... Available to patron members, become one at / funfunfunction
    💛 mpj on Twitter
    / mpjme
    💛 CircleCI (Show sponsor)
    Robust and sleek Docker-based Continuous Integration as a service. I used CircleCI prior to them becoming a sponsor and I love that their free tier is powerful enough for small personal projects, even if they are private. Use this link when you sign up to let them know you came from here:
    circleci.funfu...
    💛 Quokka (Show sponsor)
    Wonder how MPJ evaluates JavaScript inline his editor. Quokka is the answer - use this link when you buy to let them know you came from here:
    quokka.funfunfu...
    💛 FUN FUN FUNCTION
    Since 2015, Fun Fun Function (FFF) is one of the longest running weekly TH-cam shows on programming 🏅 thanks to its consistency and quality reaching 200,000+ developers.
    🤦‍♂️ The Failing Together concept is what makes FFF unique. Most coding content out there focus on step-by-step tutorials. We think tutorials are too far removed from what everyday development is like. Instead, FFF has created a completely new learning environment where we grow from failure, by solving problems while intensively interacting with a live audience.
    Tutorials try to solve a problem. Failing Together makes you grow as a developer and coworker.
    📹 Each show is recorded live on Twitch in a 2-hour livestream on Mondays. The host, assisted by the audience, is tasked to complete a programming challenge by an expert guest. Like in the real world, we often fail, and learn from it. This, of course, reflects what the audience identifies with, and is one of the most praised aspects of the show.
    ⏯ On Fridays, an edited version of the show is adapted for and published on TH-cam.
    Content Topics revolve around: JavaScript, Functional Programming, Software Architecture, Quality Processes, Developer Career and Health, Team Collaboration, Software Development, Project Management

ความคิดเห็น • 294

  • @ginoskotheon3
    @ginoskotheon3 8 ปีที่แล้ว +29

    Using LOTR characters in your examples warms my heart.

  • @scottiegrooves
    @scottiegrooves 8 ปีที่แล้ว +1

    It's always amazed my how many very smart people get tripped up by "THIS" in any programming language. Very nice explanation and examples. In 16 minutes I know what the hell bind does and where that "undefined" message comes from. Thank you very much.

  • @backnhell
    @backnhell 6 ปีที่แล้ว +28

    Ive been learning javascript for 2months now. my progress so far looks like someone staring out a kitchen window questioning the meaning of life.

  • @vampbat
    @vampbat 6 หลายเดือนก่อน

    8:15 This (pun intended) is what I have been struggling with for weeks!!! Inheritance or Composition, whatever this falls under, has been the trickiest programming hurdle I have faced in my learning. I can have dozens of global variables, but using closures and doing what you display here? Impossible! With this video, it is finally making a LITTLe sense! I am going to copy this over & over until I understand!!

  • @Erasser999
    @Erasser999 8 ปีที่แล้ว +3

    Explaining 'this' just like a common sentence was nice. Helps me understand 'this' a lot better. Without the context of a sentence, 'this' can be meaningless.

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +5

      +Erasser999 thanks! I was quite proud of myself when I thought of that analogy! ;)

  • @benjonyc
    @benjonyc 8 ปีที่แล้ว +8

    Very clear this is why I watch your channel!

  • @notdaveschannel9843
    @notdaveschannel9843 6 ปีที่แล้ว +3

    Well that's 16 minutes of my life I wish I'd spent a long time ago. Finally got 'this' into my thick skull. You Sir, have a new subscriber.

  • @psnull.
    @psnull. 8 ปีที่แล้ว +4

    Finally understood bind thanks to you. Thanks!
    See you next monday!

  • @sergiominutoli466
    @sergiominutoli466 8 ปีที่แล้ว

    It´s good to know that you can´t re-bind a bounded function.
    So, let´s say that you do
    boromir.speak = talk.bind(boromir);
    if you do later
    aragorn.speak = boromir.speak.bind(aragorn);
    aragorn.speak() // "One does not simply walk into Mordor"
    So, you´ve to be careful to know that the original function wasn´t bounded before.
    The other concern about bind is that you´re copying the function (as MPJ explained so well). If an object it´s going to be created multiple times, I´d be careful to use bind when it´s really needed.
    Great videos MPJ!

  • @JashuaWhite
    @JashuaWhite 7 ปีที่แล้ว +12

    Jack russell humping my leg. I don't like that. Roflmao! Thank you for the bits of humor and FULLY explaining concepts, step-by-step through coding examples. Helps a bunch!

  • @vaccation8073
    @vaccation8073 5 ปีที่แล้ว +1

    Thank you so much. I had so many questions before this video and the part 1. Not gonna lie, i had to rewind a lot of times to fully understand it, but you were the only one who could make me understand THIS! Keep up the ecxelent job!

  • @PaulKane85
    @PaulKane85 8 ปีที่แล้ว

    You're bound to say that this is one of the best examples of using this that there is.

  • @c0mpuipf
    @c0mpuipf 8 ปีที่แล้ว +2

    Hey mpjme, I love the way you're making these videos with hands-on code. I know this is subjective but what I'd love to see from you is to see you exploring javascript a bit further: for example take a library/framework and explain what it's doing, with code/examples in each case. I know you might have covered such topics separately but take Underscore for example: imagine explaining how each function works with examples; take AngularJS, going through dirty checking and etc.
    If I'd have your following and not be so lazy and scattered I'd do that. Something like destructuring X library/framework. This way you'd just have a lot of content to work with.
    Just a proposition I'd love to know what you think but I'd be watching those videos over and over again

  • @dl88889
    @dl88889 7 ปีที่แล้ว

    Thanks for taking the time to make these videos. You are a great presenter, and by far the only presenter where I dont have to pause/rewind the video to try and understand what has just been said. :D
    I'm relearning javascript again from the ground-up after many months of hacking Javascript stuff together without really knowing the details. Your videos are a great help!

  • @willsi
    @willsi 8 ปีที่แล้ว

    I remember when I first thought, "Hm, I wonder if you could just type 'this' into the console," and it worked. Great video, MPJ! Personally, I'm loving the series.

  • @zhenwang7380
    @zhenwang7380 5 ปีที่แล้ว

    8:06 and 10:05 and 14:50 clear explanation! I believe the core idea to understand what you will get in JS function is just simply change the reference all the way back the the original function and see if you can actually print out something or undefined.

  • @simonnice9030
    @simonnice9030 7 ปีที่แล้ว

    I'm currently studying programming at Linnaeus University in Kalmar, and I just wanted to say that your videos help me an immense amount :)! Thank you!

  • @caremyok
    @caremyok 5 ปีที่แล้ว +1

    best explanation i've ever seen. you my preciousssss teacher

  • @fbwthe6
    @fbwthe6 8 ปีที่แล้ว +4

    MPJ! Thanks for these amazing videos. I'm brand new to programming, and you're videos are a great resource for a programming bootcamp student like me. Question: Can you enlighten viewers who plan on entering the workforce what a real day on the job will be like? Your examples are simple and easy to understand, but I'm curious if you can shed some light on what a normal day in the life of a programmer is like by including some more realistic problems you regularly encounter. Even if there isn't a lot of code in the video, I'd still very much like to hear from you what you expect a junior developer to need to know as he/she begins his/her career. Thanks again! Can't wait for the next video. Also, what are you drinking today?

    • @abharti
      @abharti 5 ปีที่แล้ว

      I + this.

  • @AlisonMonteiro10
    @AlisonMonteiro10 8 ปีที่แล้ว +13

    Great video! Thanks for *this*! :P

  • @javajoint
    @javajoint 8 ปีที่แล้ว

    the one thing I would have added to this video: assign "sound" on the global object as well, to show how you reference different "sound" variables, based on the context (i.e. the context of "this" means you get one or the other)

  • @ngounthengos
    @ngounthengos 7 ปีที่แล้ว

    Your explanation is so so clear, which help a beginner like to understand a lot better. Thanks

  • @dostler001
    @dostler001 8 ปีที่แล้ว +4

    I love that example at 3:46. XD

  • @rickmedina4082
    @rickmedina4082 8 ปีที่แล้ว

    One exercise I like is to console.dir(functionName), it prints the function in its object form with all its properties including (if bound), the object is bound to and the closure (such as variables) which is specially useful while learning functional programming in OO (currying, partial application, etc.)

  • @topshot2219
    @topshot2219 7 ปีที่แล้ว

    Bravo. 1st Place in the all-time 'this' explanation category.

  • @johnnychan6755
    @johnnychan6755 8 ปีที่แล้ว

    the examples are really awesome. key takeaway for me: "functions are just values - they live on their own" :-)

  • @harini3191
    @harini3191 4 ปีที่แล้ว

    Very well explained . I have been searching in so many websites . Now i got the complete meaning.
    Thank you so much MPJ.

  • @danielbreen3945
    @danielbreen3945 8 ปีที่แล้ว

    Just watched Kyle Simpson's explanation of 'this' before your video. I was surprised to see that there weren't any conflicting points. It's always nice to have two sources teaching the same thing the same way but with different examples like you two have done.

  • @WorkingJ
    @WorkingJ 7 ปีที่แล้ว

    14:16 was when I finally GOT IT! Great last example there!

  • @Sp1derFingers
    @Sp1derFingers 8 ปีที่แล้ว +3

    Wow this is perfect. Perfectly explained, thank you!

  • @timholt152
    @timholt152 8 ปีที่แล้ว +2

    Perhaps it would be beneficial to also discuss how arrow functions do (or don't) affect 'this' context.

  • @jonyoinas1807
    @jonyoinas1807 7 ปีที่แล้ว

    Almost every single video of yours have given me that "Aha!" - moment.
    Thanks! Everything seems so much clearer now! :)

  • @ReneBroekhoven
    @ReneBroekhoven 8 ปีที่แล้ว

    Besides these really great shows as a (I think..) non-native speaker your English is top notch !
    Also I very much like your explanation of (js)this with the everyday use of (english)this. Simple but so to the point. Context is everything !

  • @anacosta5447
    @anacosta5447 3 ปีที่แล้ว

    Now every time I'll think about "this" scope, I'll imagine a Jack Russell humping on my leg...
    Thanks for that! Programming just got much more fun.
    Great video btw!

  • @jahangiriqbal3884
    @jahangiriqbal3884 5 ปีที่แล้ว

    Awesome video. One thing i noticed though: At 11:45 you comment out the bind. however if boromir.speak() were to be run even with that 'bind' commented out it will still output the sound. As expected.

  • @mikeblackfordFit
    @mikeblackfordFit 3 ปีที่แล้ว

    best teacher hands down. thank you

  • @LavanyaReddy-up2by
    @LavanyaReddy-up2by 8 ปีที่แล้ว

    Thanks MPJ.......... love your explanation .............. because it is very clear .... keep posting the videos

  • @JagoKosolosky
    @JagoKosolosky 8 ปีที่แล้ว

    Great video, I recommend reading 'Javascript: the good parts' as well.

  • @ninjaplavi
    @ninjaplavi 6 ปีที่แล้ว

    I literaly rewatched LOTR 1 and then, 10 minutes after, when i was back to code learning daily routine, i accidentally found this video with those examples. :D

  • @victorzlatin4134
    @victorzlatin4134 5 ปีที่แล้ว

    I would pay cold hard cash for lessons like these. You're an MVP man !

  • @wagnerneto8785
    @wagnerneto8785 8 ปีที่แล้ว +1

    Very nice video thank you.
    I was wondering if you can do a series with best practices in javascript ( and the why of them ), i think that will be very interesting and help a lot of people.
    See you in BrazilJs ;)

  • @robscherer
    @robscherer 2 ปีที่แล้ว

    Literally laughing out loud when going back and watching these videos...the jack Russell comment!!! haha

  • @mustang19ms
    @mustang19ms 3 ปีที่แล้ว

    Beautiful videos, you're great at explaining and funny too

  • @QWEEKEN73
    @QWEEKEN73 6 ปีที่แล้ว

    How I got it to click was understanding that - " 'This' references the object that called the function, by default. Unless you bind it to a set object"

  • @MrVadimster
    @MrVadimster 7 ปีที่แล้ว

    Just if anyone did not get why gollum.jabber() returned “My precioussss…”. This happened because gollum.jabber() is referenced to talk() via a number of references, BUT “this” key-word is always linked to the object which invokes a method. In this case the object was gollum{}, so his “sound” attribute will be used. So, to understand what THIS will mean one needs to see what the object is starting a function call.

  • @WiBla
    @WiBla 8 ปีที่แล้ว

    Hey Mathias, I discovered your channel very recently (had a ton of fun BTW) and I was wondering:
    Is there an order on wish to watch your playlists ? Like going from the basics to more advanced stuff, or could we watch them as we want ?
    Also, will you cover (maybe not in full detail) more basics features ? (I ask this because I think you will do a great teacher and covering the basics with you will be very cool)
    Your let's code series is probably my favorite, you truly deserve more subs ;)

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +1

      +MrWiBla there is no particular "starting" playlist, it's what you're interested in.
      The lets code series is indeed very nice, but it's tricky to do, haven't figured out a way that doesn't kill me. ;)
      I probably won't be doing more basic features as I feel that segment is very saturated already, and my subscriber audience is largely intermediate programmers - I'm afraid it would alienate them.

    • @nicholasspinosa3907
      @nicholasspinosa3907 8 ปีที่แล้ว

      I think watching the functional programming Playlist from start to finish a few times is a good start. You could keep up with this lost as well because they don't depend on each other.

  • @vigneshsrinivasan3992
    @vigneshsrinivasan3992 8 ปีที่แล้ว

    video is good.
    Can you talk below topics more.
    1) Memory management in JS
    2) Prototype
    3) OOP concept in JS

    • @mackenziebruce3639
      @mackenziebruce3639 7 ปีที่แล้ว

      vignesh srinivasan he would probably explain it better than me but
      when you create a variable:
      var a = 10;
      var b = a;
      var a = 30;
      if you console.log() a and b, a = 30 and b=10. JS makes copies of the spot in memory and assigns it for variables.
      with functions JS stores a function into memory and the new function shares the same spot in its memory management

  • @sylvain1099
    @sylvain1099 8 ปีที่แล้ว

    Awesome, the last example smashed me for a while;)

  • @UdeyRishi
    @UdeyRishi 8 ปีที่แล้ว

    I have worked with classical OO languages, and am now learning JavaScript and its prototypical OO structure. I recently learned that ES6 introduced classes. I read some examples on SO, and I am not sure if I fully understand if classes, as a concept, belong in the language. Can you do a video on JavaScript classes, and what you think about those?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +1

      +Udey Rishi this series will absolutely have a segment on classes.

    • @UdeyRishi
      @UdeyRishi 8 ปีที่แล้ว

      +funfunfunction Thanks, and great job with these videos! I'm a fan!

  • @andrebillrm
    @andrebillrm 8 ปีที่แล้ว

    Fantastic video! super entertaining and very clear. I think bind() was the information i needed for a current bug in a personal project, gonna try it out. Keep up with the nice content !
    (also, are you on Quora? think i saw you there)

  • @marcusvindictus
    @marcusvindictus 7 ปีที่แล้ว

    Thank you for the videos! I feel that you missed the final illustrative step in this video.
    let boromir = { sound: 'One does not simply…' }
    boromir.blabber = talk.bind(boromir)
    let gollum = { jabber: boromir.blabber, sound: 'My precious' }
    gollum.jabber() // One does not simply…
    This helps clarify what bind does to the context.

  • @MatthewDeaners
    @MatthewDeaners 6 ปีที่แล้ว +1

    By the way, this won't throw an error:
    -----
    var talk = function() {
    console.log(this.sound)
    }
    var boromir = {
    speak: talk.bind(boromir),
    sound: 'One does not simply walk into Mordor!'
    }
    boromir.speak()
    ------
    It's the use of "let" that causes the "boromir is not defined" error, because it has no in-place value. Buuuuut because of how variable hoisting works, even though you get no error, boromir.speak() will output "undefined". Fun!

  • @vasylstokolosa3958
    @vasylstokolosa3958 8 ปีที่แล้ว

    Hi, MPJ!
    You have videos about Functional Programming but there are only small parts (map, reduce ...). Would be better to see some architecture approaches. For e.g. build Calculator on Functional Programming paradigm and Object-oriented. Then compare, advantages, disadvantages.
    If you have some, please share :)
    Thanks!

  • @ishaqorakzai9571
    @ishaqorakzai9571 5 ปีที่แล้ว

    let obj = {
    sound : "ko ko",
    name : "Bird",
    }
    let speak = function() {
    return obj.sound; // ====> this.sound
    }
    let bound = speak.bind(obj);
    console.log(bound())
    // for better understanding lol . i hope it will help u out what this is refering to ;)

  • @AndrewWhiteProfile
    @AndrewWhiteProfile 8 ปีที่แล้ว +1

    If `this` still does not make sense, go watch MPJs previous video on this topic and see how he moves the function referring to `this` into the context which it is called (at time: 10:51s). This is when I "got it".
    th-cam.com/video/GhbhD1HR5vk/w-d-xo.htmlm51s

  • @apocalypseio
    @apocalypseio 8 ปีที่แล้ว

    Totally addicted to FFF! Crossing my fingers this miniseries will explore both new and Object.create

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว

      +Chris Hughes it definitively will!

  • @DrempDK
    @DrempDK 8 ปีที่แล้ว

    _this_ = the best explanation I've come across that clearly explains _this_ properly. _this_.thank(Mattias)

  • @matthewsmith7606
    @matthewsmith7606 7 ปีที่แล้ว

    Question about function vs object 'this' scoping. From my understanding, in normal functions "this" is going to refer to whatever called the function (assuming it's not enclosed in an object, so this would probably be window or whatever). Within an object "this" inside of a function inside the object would refer to the object itself.
    my biggest confusion is around "this" inside methods, it should still refer to the object it's inside correct? (this all assumes your not using ES6 arrows). For instance a function inside a function that refers to this.....will probably refer to the window/global object unless you bound it to a different object?

    • @funfunfunction
      @funfunfunction  7 ปีที่แล้ว +1

      +Matthew Smith you might want to watch the previous videos, this stuff is all in there.
      1. There is no "normal" function in JavaScript, it's just functions.
      2. There is concept of "enclosing" a function in an object in JavaScript.
      3. this does NOT refer to what called the function.
      4. If a function (and remember that a function is just a value that can be assigned to a variable or a property, just like an int or a string) is assigned to a property on an object and that property is called on the object, then that object will be this. However, if you call the same function on its own, this will be something else. Assigning a function to the property of an object does not bind it to the object, this is completely determined by how it's called.

  • @leonslacker
    @leonslacker 8 ปีที่แล้ว +2

    Thanks MPJ!! You are a JS Rockstar ^^

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +66

      I should break a keyboard every episode.

  • @cboisvert2
    @cboisvert2 4 ปีที่แล้ว

    4:00 "your Jack Russel..." - can't listen anymore, laughing too much

  • @abahiduh3246
    @abahiduh3246 2 ปีที่แล้ว

    To understand the 'this' keyword, Note, that all 'this' in a function or method refer to the OBJECT that is invoking the function or method.... every function definition or method CAN be invoked by an OBJECT.

  • @PENDANTturnips
    @PENDANTturnips 7 ปีที่แล้ว +1

    Great intuitive examples!

  • @Adoroam
    @Adoroam 7 ปีที่แล้ว

    Have you ever thought about making an atom snippet for console.log()? I just type clog and press tab and it puts my cursor right in the parenthesis. Makes things so much faster.

    • @funfunfunction
      @funfunfunction  7 ปีที่แล้ว +3

      I intentionally avoid hotkeys and clever plugins in the videos. Whenever I use any kind of tool people wonder how I did it and it distracts from the the main narrative of the video. In this case specifically, I also don't like to contribute to the widespread myth that typing speed is in any way related to programmer productivity.

  • @sashajustice
    @sashajustice 8 ปีที่แล้ว +1

    Hey Mattias!! Thanks for these awesome, incredibly helpful videos!

  • @jakobengberg-pedersen4457
    @jakobengberg-pedersen4457 8 ปีที่แล้ว +2

    Could you make a video on unit testing please?

  • @rebornreaper194
    @rebornreaper194 6 ปีที่แล้ว

    The signs are a great idea. Very gabby ;)

  • @gregorianwolf2631
    @gregorianwolf2631 8 ปีที่แล้ว

    MPJ if you had used 'var' instead of 'let' then would boromir.speak have being defined because of hoisting @ around 11:12

  • @xstreamkd
    @xstreamkd 8 ปีที่แล้ว

    I love your console prompt

  • @McG00f
    @McG00f 8 ปีที่แล้ว

    Very good teacher.

  • @MrBotv0091
    @MrBotv0091 8 ปีที่แล้ว +1

    Hey MPJ, i hope in your series you describe about this and arrow function? Thank you.

  • @nathancornwell1455
    @nathancornwell1455 4 ปีที่แล้ว

    if talk() was an arrow function, that would also change the value of this. I try use bind in that situation but i still get undefined . I understand why cuz of the rules of arrow functions but how do you fix that ?

  • @WenbinLinx
    @WenbinLinx 7 ปีที่แล้ว

    var talk = function () {
    console.log ( this.sound );
    }
    var haha = {
    sound: "lol",
    speak: talk.bind(this)
    }
    haha.speak()
    In this case, "talk.bind(this)"'s "this" is still window object when haha.speak() is called, right?

  • @eh1255
    @eh1255 7 ปีที่แล้ว

    Do you have any videos on understanding references vs. values in JavaScript? If not, I'd love to see one!

  • @VictorCruzReis
    @VictorCruzReis 4 ปีที่แล้ว

    Hi,
    When am I using arrow functions I don't need to use bind, correct?
    Can I use arrow functions in every scenario when I don't need the caller context?
    Thank you!

  • @SamChaneyProductions
    @SamChaneyProductions 5 ปีที่แล้ว

    So basically, without using bind, the 'this' keyword will always refer to the object from which you are calling the function or property? So if you created a function that added a property to an object via 'this', it would add it to whatever object you called it on? So if you were in a browser and called it by its self it would add it to the window object? Seems like 'this' can be dangerous if used without bind unless you're very careful.

  • @sahandsanaei555
    @sahandsanaei555 ปีที่แล้ว

    superior teaching as always!

  • @jonasabreuresenes
    @jonasabreuresenes 8 ปีที่แล้ว

    Hi MPJ, I saw that you will be on BrazilJS this year. Let's have a lunch, we have the best barbecue of the world here in Porto Alegre :)

  • @cuddles3057
    @cuddles3057 8 ปีที่แล้ว

    MPJ,I remember you saying something along the lines of "I'm a God with C#" (not accurate, at all, but good enough for me). Would you do some videos on C#??? Please!!!!

  • @SJ-gm7oh
    @SJ-gm7oh 7 ปีที่แล้ว

    thanks for great video. i got a question while watching video.
    in video, you said speak(function) is not copying talk(function), it referencing.
    but if we redefine talk(function), speak(function) still returning same result. if speak is referencing talk, shouldn't it be changed as talk changes?
    why it is? thanks.
    ------------code-----------------
    var talk = function(){console.log(this.sound)};
    let boromir = {
    speak: talk,
    sound: 'initial'
    }
    boromir.speak() // initial
    talk(); //undefined
    var talk = function(){console.log("changed")}
    boromir.speak() // initial

    • @funfunfunction
      @funfunfunction  7 ปีที่แล้ว +2

      What you're seeing in your example is just how references work in programming languages. It's easier to see if you make a simpler example:
      let catsound = 'meow'
      let sound = catsound
      console.log(sound) // 'meow'
      catsound = 'woof'
      console.log(sound) // still 'meow'!
      console.log(catsound) // 'woof'!
      Maybe the mistake you're making is that you are thinking of variables as the things themselves, but they are just addresses. So on this line...
      var talk = function(){console.log("changed")}
      ...you are not changing talk, you're creating a new function, and then you point the address talk to that new function. This will not affect boromir, because when it was created, talk was pointing to the old function, and thus the address boromor.speak is now pointing to that old function.
      Another way of thinking about it is that variables in programming languages don't build "chains", you point a variable to a value, but you cannot point a variable to another variable that in turn points to a value. When you do this ...
      let boromir = {
      speak: talk,
      sound: 'initial'
      }
      ... then boromir.speak is NOT pointed to "talk", it takes whatever talk is pointing to, and points boromir.speak to it. So your mental model is that this is what happens:
      talk -> function(){console.log(this.sound)};
      boromir.speak -> talk -> function(){console.log(this.sound)};
      but in reality this is how the things relate:
      talk -> function(){console.log(this.sound)};
      boromir.speak -> function(){console.log(this.sound)};
      I.e. there is no interim variable, the variable is reassigned.

  • @stephandevries5069
    @stephandevries5069 7 ปีที่แล้ว

    So at 14:50 gollum.jabber refers to the this.sound of the gollum object because it was called from that initial object? Even though it might seem from the context of the talk function it might have been boromir since it called the function last?

    • @funfunfunction
      @funfunfunction  7 ปีที่แล้ว

      I'm not entirely sure if I understand your question. Can you elaborate? I get confused by your terms "initial object" and "context".

    • @stephandevries5069
      @stephandevries5069 7 ปีที่แล้ว

      By "initial object" I mean the first object being called from that entire chain. And by "context" I mean "which object is calling which".
      But I guess the only thing that really matters is the initial call, since even though gollum.jabber chains all the way through to the talk function, the talk functions "this" changes to the gollum objects context(this).
      That probably didn't make everything a whole lot clearer haha.
      Thanks for these video's though I really appreciate it. Means a lot that somebody is willing to share their wealth of knowledge when they have a full time job and properly not a lot of time to spare. Thanks!

  • @devdive7293
    @devdive7293 6 ปีที่แล้ว

    So can I use console.log(this) instead of console.log(document.defaultView); ?

  • @MillerGonzalezGeeklancers
    @MillerGonzalezGeeklancers 7 ปีที่แล้ว

    what happens with the strict mode defined inside into the function

  • @Champignon1000
    @Champignon1000 8 ปีที่แล้ว

    PLEASE do a tutorial on neural networks.

  • @griimick
    @griimick 4 ปีที่แล้ว

    This is such a great show. Thank you for creating this.

  • @GuillermoValleCosmos
    @GuillermoValleCosmos 8 ปีที่แล้ว

    At 11:15, could you have done `speak: talk.bind(this)` ?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +2

      +Guillermo Valle no. When executing line 5, this is just the global/window object. Note that were just creating an object literal here.
      You are probably confusing the code here with examples that you have seen that do binding to this inside the constructor of a class, and that does some magic shit with this - we will be getting to that later in the series.

  • @sarthaksrivastav3408
    @sarthaksrivastav3408 5 ปีที่แล้ว

    Awesome explanation

  • @goranudosic8420
    @goranudosic8420 8 ปีที่แล้ว

    Just noticed that I have posted on the previous video :) Anyways.. maybe someone will find it useful:
    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.

  • @willb.755
    @willb.755 7 ปีที่แล้ว

    Such a great teacher :D Love all the funny examples to connect it to real life!

  • @Misfittykitty
    @Misfittykitty 3 ปีที่แล้ว

    What a fantastic explanation! I commend you! :)

  • @ltadeut
    @ltadeut 8 ปีที่แล้ว

    Always fun to begin my mondays with your videos hahah.
    Great examples :-)

  • @axMf3qTI
    @axMf3qTI 8 ปีที่แล้ว

    When we write fat arrow functions does js automatic bind the parent object to the function in the background? And where do you get those shirts of yours?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว

      +axMf3qTI not quite. When an arrow function is declared, it binds this bound to the context where the arrow function is created. I.e. Whatever 'this' is when you create the arrow function, will also be 'this' when you call it. In most examples that show arrow functions this also happens to be the parent object, which causes you to get the impression that there is a connection (that and the fact that the examples emulate classes where there actually is such a connection in other languages) In fact, the whole terminology of parent is a bit misleading since it implies that the function "belongs" to the parent. In fact, since functions can be passed around as variables and arguments to other functions, a function can have 842 parents, which means that the concept of binding to "parent" makes less sense.

  • @MrVankog
    @MrVankog 7 ปีที่แล้ว

    What's the difference if we omit "this" in these examples?
    So just "sound"?

  • @L8rCloud
    @L8rCloud 6 ปีที่แล้ว

    With boromir.speak() the object boromir is passed to 'this' within the talk function...WHAT IF you wanted to pass a specific object other than the inferred boromir OR default Global?
    When you go further with blabber you bind again. With three levels of creation this is ok but WHAT IF we did this 1000 times? Is there a way to automate this step and run it through a custom bind process?

    • @funfunfunction
      @funfunfunction  6 ปีที่แล้ว +1

      In that case, use bind or call to change the scope of this. However, if you find yourself in that situation, I would honestly question if you aren't using OOP for no good reason and would be better of with just a plain, simple, elegant function.

  • @kimk.m2428
    @kimk.m2428 7 ปีที่แล้ว

    when boromir.speak=talk.bind(boromir),how the H does javascript know to automatically transition the output to the "speak:one does not simply ...." in boromir?

    • @kimk.m2428
      @kimk.m2428 7 ปีที่แล้ว

      ...as an addition, what if boromir={speak:"One can simply walk over", shout:"BOROMIRRR!"} ?What would the output boromir.speak=talk.bind(boromir) of be?

  • @himitsumonban
    @himitsumonban 8 ปีที่แล้ว

    So I'm confused by one thing. You say that "this" is bound at the time of the function call. In the last example the function is called from the global scope. Yes it got passed around as a reference through the boromir object, but the actual call was made outside all objects. I predicted "undefined" as the result, but somehow it seems like it was bound to the gollum object... How? Why?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +1

      On line 12 at 14:45 - it's because we're calling the property jabber on the gollum object - when a property points to a function, and we call that property on the object, the rule is that the object that has the property becomes the "this". It's not bound to gollum, if we call boromir.blabber() just below, it would have said "One does not simply walk into mordor" because then this would have been boromir - the function is not bound in that example, it's completely defined at the time of the call.

  • @DefWorlds
    @DefWorlds 8 ปีที่แล้ว

    How do callbacks (for input events, say) work if they are bound to the this associated with an object? Does this clobber the $event argument? How can one access $event in the callback?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว

      +Adam S Angular messes up JavaScript beyond recognition and I have no idea. You have to ask Angular people about this.

  • @N7Martin
    @N7Martin 8 ปีที่แล้ว

    So basically 'this' points to an object from which the function was called. Parent object for talk() is window if you execute this function in global scope. If you execute boromir.speak() then boromir becomes the parent for 'talk'
    Am I right?

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +3

      +N7Martin yes. I prefer he word context to parent though - because the word parent implies singularity - you only belong to one or two parents. There is no parent object for functions. A book has an author, but a sentence generally does not have an "author", many people can use it.

  • @LucasBernardodeSousa
    @LucasBernardodeSousa 7 ปีที่แล้ว

    Oh man, is that a Simon Stalenhag on that wall? Very nice taste indeed

  • @tonysolomonik
    @tonysolomonik 8 ปีที่แล้ว +1

    New tokyo machine song, i like it !! Great video man :)

    • @funfunfunction
      @funfunfunction  8 ปีที่แล้ว +1

      +Tony Solomonik golden star for recognizing the song!

    • @tonysolomonik
      @tonysolomonik 8 ปีที่แล้ว

      lol such a weird but cool song, by the way check out my latest "I am bored let's sketch in p5.js" creation: tontinton.github.io/bubble_sort/Bubble%20Sort/

  • @JacobMGEvans
    @JacobMGEvans 6 ปีที่แล้ว

    I love your videos, glad you reduced (pun intended) the background music.