Factory Functions in JavaScript

Поделиться
HTML-код
  • Опубликовано: 13 сен 2015
  • 💖 Support the show by becoming a Patreon
    / funfunfunction
    Video transcript and code examples here:
    / d38e49802555
    💛 Follow on Twitch
    We record the show live Mondays 7 AM PT
    / funfunfunction
    💛 Fun Fun Forum
    Private discussion forum with other viewers in between shows. www.funfunforum.com. 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.funfunfunction.com
    💛 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.funfunfunction.com
    💛 FUN FUN FUNCTION
    Since 2015, Fun Fun Function (FFF) is one of the longest running weekly RUclips 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 RUclips.
    Content Topics revolve around: JavaScript, Functional Programming, Software Architecture, Quality Processes, Developer Career and Health, Software Development, Project Management
  • НаукаНаука

Комментарии • 555

  • @nosajghoul
    @nosajghoul 8 лет назад +216

    If you paired up with the guy who wrote 'You dont Know Javascript', the concepts would be so well explained they could air it on Sesame Street.

    • @emilywilliams6403
      @emilywilliams6403 7 лет назад +18

      Kyle Simpson!

    • @regularwebguy6414
      @regularwebguy6414 6 лет назад +2

      Ha ha Javascript Sesame Street

    • @jidaasare7021
      @jidaasare7021 5 лет назад

      This just made me burst out loud !!!! lol

    • @frankvee
      @frankvee 5 лет назад

      That is just as funny as the guy on the video. Thanks for the laugh. :)

  • @michaelguild
    @michaelguild 5 лет назад +11

    I am a Sr dev and have been coding for about 13yrs. I discovered your channel while looking up good js videos for refresher's and interns. I have to say, out of everything out there, this is one of the few channels that really does a good dive into the language. Keep up the awesome work :)

    • @carminetambascia6355
      @carminetambascia6355 2 года назад

      unfortunately the stopped producing content for a full time job. What a shame.

    • @michaelguild
      @michaelguild 2 года назад

      @@carminetambascia6355 I thought she quit coding all together to just chill. Pretty sure he's making good passive income at this point :)

  • @tilakmadichettitheappdeveloper
    @tilakmadichettitheappdeveloper 8 лет назад +58

    Thanks for 2 reasons:
    1) For learning English
    2) For teaching in a simple way !

  • @Adam.Garrett-Harris
    @Adam.Garrett-Harris 8 лет назад +34

    Great videos! I discovered this channel last night and watched all of them!

    • @funfunfunction
      @funfunfunction  8 лет назад +14

      +Adam Harris Wow, awesome! Welcome to the channel! :)

  • @ericromanenghi6346
    @ericromanenghi6346 8 лет назад +2

    wooooooooowww it's awsome! I was watching all the functional programming videos, and i love them! I only implemented functional prog in Haskell before see your videos, and now i will consider to use javascript in the future!

  • @jonl3578
    @jonl3578 8 лет назад +62

    The speed of the factory vs class instantiation isn't really an issue, it's the memory footprint that you should be mindful of. The issue is that an object factory returns completely separate objects that repeat all of the same code, rather than all referencing the class blueprint. This eats more memory.

    • @funfunfunction
      @funfunfunction  8 лет назад +25

      +Jon L It's the same thing with memory. If you're doing tens of thousand of them per second, it's relevant. Otherwise, no. Computers are fast.

    • @autochton
      @autochton 8 лет назад +2

      Example I faced in the Real World(r): Contact database containing thousands of entries. Memory breakdown at ~16K entries, some customers had ended up with 100K+ due to import from previous system. Definitely Flyweight time, and that is more easily done with a prototype to furnish functionality.

    • @samybounouar1979
      @samybounouar1979 4 года назад +5

      @@autochton I those cases you could have used a generator or a stream approach as well. If you have 2Go of data, you wouldn't be able to use either prototype or class, you would need a pointer.

  • @mr.w7803
    @mr.w7803 8 лет назад

    I really like your show! I've been developing for a while and watching it has made me more confident in my abilities. I'm learning new terms and techniques for things I've been doing already haha. Thanks!! 🙂

  • @HariShekhar
    @HariShekhar 5 лет назад +1

    Again a superb video. You have made factory functions so simple. Thank you

  • @wishmaker1443
    @wishmaker1443 5 лет назад +1

    This is an incredible description! Thank you!

  • @zackoncode1261
    @zackoncode1261 4 года назад +1

    You just earned my subscription because you give attention to some of this little concepts in programming which is very important to any Software Engineer Junior or Senior...

  • @seancampbell5641
    @seancampbell5641 8 лет назад +2

    Just thanks again for putting the work into these videos. Helps a lot

  • @lifeacoeur7037
    @lifeacoeur7037 8 лет назад +6

    Thanks for this amaaaaaazing channel ! Very clear speech, informative content, shitty humour...
    Actually english not being your native language makes your videos clearer and a lot easier to understand for non-native english speakers and especially for dumb french people like me :)
    Please keep doing such a good job !

  • @ruslansataiev9882
    @ruslansataiev9882 8 лет назад +2

    As always concise, clear and useful. Thank you :)

  • @velocity1186
    @velocity1186 5 лет назад

    Thank you so much for this video. Got asked to create some factory functions solve something at work and I was a bit lost until I found this video.

  • @fhmtz
    @fhmtz 8 лет назад +1

    Excellent video! Thank you!!! You're the best!

  • @MrCentripetal
    @MrCentripetal 8 лет назад

    I love your channel. You learned me so much stuff in a such simple and elegant way ! :)

  • @MapMavericks
    @MapMavericks 8 лет назад

    I LOVE your videos and your style. Thanks for making programming easier!
    CHEERS

  • @irmoathlete
    @irmoathlete 8 лет назад

    You deserve more subs, your explanations are great. Keep up the good work.

  • @softengi4043
    @softengi4043 8 лет назад +3

    I like how you got out of a bar and decided "hey I'm going to make a programming video!" haha. Nice wrist band. And nice vid too.

  • @BigBoxRetroCollector
    @BigBoxRetroCollector 5 лет назад

    These videos are awesome! Thanks a lot. This is the ultimate resource for a developer, and especially for front end devs.

  • @wodemoshou
    @wodemoshou 8 лет назад

    This is awesome! Thanks for sharing and teaching!

  • @venicebeachsurfer
    @venicebeachsurfer 6 лет назад

    "my gentle soul. It looks like chit"!! lololol. Love it.
    I like your style. You teach well, and effectively convey poignant points easily. Good job.

  • @BrettCoffin
    @BrettCoffin 8 лет назад +1

    You can freeze the "this" in your Class via the BabelJS "es7.classProperties".
    ie: talk = ()=>{ console.log(this.sound) };
    And thank you for your work ! Keep it going it's great !

  • @jongeduard
    @jongeduard 5 лет назад +2

    Thank you for you clear explanation!! Also for your next video (Composition over Inheritance)!
    I have started learrning JavaScript many years ago (it was actually the first programming language that learned), but it was followed by Java and also C/C++ and some other languages not long after.
    For years I have mainly programmed in C# now and also done Delphi, and a lot of SQL.
    Looking back at JavaScript after such a long time and searching around on the internet for the newly added features in ECMAScript 6, I can only say that a lot has changed! Several features (like the lambda function expressions) from other languages have also been added to JS now.
    But when looking at the OOP part of JavaScript and all the limitations that it has, especially when using the "class" "new" "this" way, which is the way that we are so used to from the other programming languages (Java, C#, C++ and many more), I personally think the OOP thing in JavaScript has just not been finished, it's just not complete.
    For me it feels actually very weird that there is not a normal/intuitive way to make variables private like in the other programming languages.
    To many things have to be solved with tricks, like closure, and that weird bind() and call() functions.
    Things are understandable, but very confusing.

  • @tadeoriverosk
    @tadeoriverosk 7 лет назад

    You're a great guy! Thanks so much for doing this!

  • @FictionsAndIllusions
    @FictionsAndIllusions 6 лет назад

    Thanks for posting this video. I've heard of the phrase "factories" in Clean Code book, which is Java based. I didn't understand what it meant or what it does, but now I think I have an idea and I can do this in JavaScript!

  • @lfriedrichsen
    @lfriedrichsen 6 лет назад

    Awesome!! Thank you!! Would love to see more episodes with more function factory examples like a function factory combined with the addEventListener method for use on a web page. Perhaps you have several buttons on a web page, and you need them to run the same function, but you want to pass in different parameters. I can't figure out how to do it without using 'this'. I'm sure you can though!! Thanks for ALL of your great videos!!!!

  • @ianjamiesonmusic
    @ianjamiesonmusic 7 лет назад

    Very clear, concise, accurate and informative.

  • @jakewilson1070
    @jakewilson1070 8 лет назад +8

    Wow how have I never stumbled across your videos before? Good stuff, informative, educating and funny :-)

  • @jc-depre
    @jc-depre 8 лет назад

    great video, simple as it should be, thanks mpj

  • @diwu183
    @diwu183 8 лет назад

    Really nice! Thanks for sharing about this!

  • @joshuavanmeer2002
    @joshuavanmeer2002 7 лет назад

    This is awesome. Had a good grasp of this binding, but feels like this was the last missing piece of the puzzle.

  • @baharmand
    @baharmand 7 лет назад

    Very informative, thanks for the clear explanations.

  • @zebcode
    @zebcode 7 лет назад

    just discovered your channel. amazing! thank you!

    • @funfunfunction
      @funfunfunction  7 лет назад

      +Kiran Randhawa thanks for tuning in, Koran! Glad to have you here!

  • @mileswarburton9676
    @mileswarburton9676 8 лет назад

    Great videos, I really like your method of teaching.

  • @ZawWinnHlaing
    @ZawWinnHlaing 8 лет назад

    it's a great series and thanks you for sharing @mpjme. i'm stay curious :D

  • @ivanmatvieiev8146
    @ivanmatvieiev8146 8 лет назад

    Best channel about JavaScript that I ever seen!

  • @nchecker00
    @nchecker00 6 лет назад

    whatching your vids not to learn js, but to cheer yourself up

  • @userJorgeCarmine
    @userJorgeCarmine 6 лет назад

    Hi, I'm learning JavaScript and English, with your channel I can learn about both

  • @ClemmonsX
    @ClemmonsX 6 лет назад

    it was what I have looking for from long time :) thank you man

  • @DannyFeliz
    @DannyFeliz 8 лет назад +7

    YOU CRACK ME UP at 01:53 Jaja.
    Really nice video video

  • @uclastudentservices309
    @uclastudentservices309 6 лет назад

    Another very good tutorial! Thank you!

  • @scottldn
    @scottldn Год назад +1

    Still relevant, and still the best resource for breaking down JS concepts imo

  • @ekaterinahorton768
    @ekaterinahorton768 4 года назад

    Great clear video, thank you very much! Subscribed :)

  • @kevincarr2334
    @kevincarr2334 7 лет назад

    Thank you this was a great and educational video!

  • @surajit96
    @surajit96 7 лет назад

    By the way, I watched lot of your videos lately and totally loved them!!

  • @AlexQuirk
    @AlexQuirk 8 лет назад +1

    Really great stuff, good work

  • @tenstairs
    @tenstairs 5 лет назад

    So good! I wish I started watching your videos years ago. Better late than never though

  • @santosharakere
    @santosharakere 8 лет назад +1

    Great video. Thank you.

  • @Revolution3030
    @Revolution3030 2 года назад

    This video solves a problem I've been working on for a week with websockets

  • @SergeofBIBEK
    @SergeofBIBEK 7 лет назад

    I'm sold. I'll be doing this instead of the prototype nightmare from now on.

  • @ShaneCrouch
    @ShaneCrouch 5 лет назад

    Great video, thank you. A little bit cleaner but still similar bind ugliness is to do this below, putting your binds in the constructor, that way any client of your Pet API does not have to know about it. It is hidden. I wonder why frameworks such as ReactJS using the classes a little. MyReactComponent extends React.Component {}; . They must be using a design pattern such as a GoF Template Pattern, which is maybe easier to implement using classes. Not sure, I have been meaning to dig into the why.
    class Pet {
    constructor() {
    this.sound = 'woof';
    this.talk = this.talk.bind(this);
    }
    talk() {
    console.log(this.sound);
    }
    }

  • @josepservat211
    @josepservat211 7 лет назад

    great job as always !!

  • @sawomirbudzynski8914
    @sawomirbudzynski8914 5 лет назад +1

    Better example would be if you will pass some parameters to this factory function and then they would be private variables. This would be really competitive to classes. I like both approaches and diversity and speed of JS.

  • @GodOfMacro
    @GodOfMacro 8 лет назад +1

    It's good to note that you can also have factory that use shared prototypes with es5 "Object.create(proto)" so you avoid re-creating part of common code, but that won't free you from "this" so it's not prefect...
    Also making part of your object in a common separated object can be done for performance, where you can pass your object to the common methods instead of having them nicely on your object directly.
    A bit less expressive, but avoid the trap of this.
    Not sure I made perfect sense here, hard to do without propers exemples but, even in the case of performance benefices, you can avoid classes.

  • @yomasanamae5433
    @yomasanamae5433 6 лет назад

    great episode this is too! i’m watching this series and try it one by one.

  • @Vintharas
    @Vintharas 8 лет назад +3

    Great video! Keep them coming! ^_^

  • @Webschool-io
    @Webschool-io 8 лет назад

    Wonderful channel congratzzz!!

    • @funfunfunction
      @funfunfunction  8 лет назад

      +Webschool - JavaScript thanks a lot for your kind words. :)

  • @LearnFrontendNow
    @LearnFrontendNow 4 года назад

    Only MPJ could make Factory Functions this fun 😂

  • @geocine
    @geocine 7 лет назад +14

    I was wondering are you planning to create a paid course so we would have the opportunity to donate? I have never seen a programming video as entertaining, concise yet very clear as yours.

    • @funfunfunction
      @funfunfunction  7 лет назад +7

      +geocine thanks! I have something like that in the works.

    • @artgreg2296
      @artgreg2296 6 лет назад

      on patreon you can donate www.patreon.com/funfunfunction

  • @matewilk
    @matewilk 8 лет назад +1

    Thanks a lot for the video, it cleared a lot for me, especially the Crockford's idea to not to use classes, nor "this" keyword, as it was a bit of a mystery form me, although I have been using factory functions a lot without knowing their proper naming, until this point ;)
    I would also add, that nowadays, in framework's world, you are bound to use their concepts of writing code, so I use factory functions mainly for writing my own helpers. But I'm happy to hear, where else can I use them ?

    • @funfunfunction
      @funfunfunction  8 лет назад +3

      Well, the point of having a framework is that you build within its style and parameteters. This is why I'm not a huge fan of frameworks. ;) That said, I've been having a lot of fun with Redux which only deals with functions and data object. Mind-blowingly nice

  • @wagnermoreira786
    @wagnermoreira786 5 лет назад

    awesome explanation!

  • @SuperCotik
    @SuperCotik 8 лет назад

    Hello Mathias,
    I really like your show, and agree with most of your points of view.
    Considering the factory pattern, how do you mix it with the EventEmitter pattern in node ?
    I mean, when you want your instances to emit events, you can't util.inherits(EventEmitter) because, if I'm right, util.inherits takes a constructor as a parameter.
    So how do you deal with that aspect ?
    Thank you ! And keep doing what you do :)
    Cheers

  • @Saturdayreview98
    @Saturdayreview98 Год назад

    You are my life(time) saver
    Thank you very very much

  • @miheymik7984
    @miheymik7984 8 лет назад

    cool. thank you a lot for the explanation!

  • @davidsaint8866
    @davidsaint8866 5 лет назад

    LMAOOOO!!!! 2:08 made me subscribe, turn on notifications and like this video.

  • @wishmaker1443
    @wishmaker1443 4 года назад +6

    "It hurts my gentle and beautiful soul to look at this code - it looks like... the shit!" - awesome! :))))

    • @collin_ph6023
      @collin_ph6023 4 года назад +1

      That's gramatically incorrect. When adding "the" in front of the "S" word, it implies that the thing is good. The word "the" in this instance, should be omitted.

    • @alimertc
      @alimertc 4 года назад +1

      @@collin_ph6023 but it sound more french that way

    • @88Timur88Bahmudov88
      @88Timur88Bahmudov88 3 года назад

      @@collin_ph6023 he is not a native speaker, so he probably didn't know about it at the moment of recording the video

  • @OhadS
    @OhadS 8 лет назад +2

    Hey Matthies!
    I really like your channel watched many of your videos they all were exciting and interesting.
    I have a question,
    In case I want to construct mutable objects is it possible to use factory as well or should I go with classes?

    • @chenrvn
      @chenrvn 8 лет назад +1

      1. For functions that are "shared" between objects u dont need mutable objects But for saving state inside the object, u right there is a bit problem. u solve it by object.create and object.assign + see the episode regard to composition.

    • @funfunfunction
      @funfunfunction  8 лет назад +1

      Hi Ohad!
      No problem at all. If you change sound to be let instead of const you can change it just fine:
      const dog = () => {
      let sound = 'woof'
      return {
      setSound: newSound => sound = newSound,
      talk: () => console.log(sound)
      }
      }

  • @avimehenwal
    @avimehenwal 3 года назад

    great video. Between I wanted to know how to measure how much time did JS took to instantiate a class or a factory function on my computer? How did you measure those numbers?
    They looks cool

  • @tylerharden2152
    @tylerharden2152 8 лет назад

    @mpjme great video! thanks for making it. I understanding using factories over classes is more common/preferable with front-end javascript, however what is your opinion on using classes in the backend. What instances would you recommend using a class outside of the one described in the video?

    • @funfunfunction
      @funfunfunction  8 лет назад +2

      +Tyler Harden My advice does not change if it's on the frontend, backend, or in an Arduino. If you're creating hundreds of thousands of items per second, use classes. Otherwise, use factories. Always write as simple code as you can get away with, and only reach for clever, optimized code when you actually need it.

  • @michaelmbah4952
    @michaelmbah4952 8 лет назад

    Awesome video. really nice!

  • @GrantGryczan
    @GrantGryczan 6 лет назад +1

    I love this channel. 😄

  • @josher3436
    @josher3436 8 лет назад

    Great video, thanks Dude.

  • @dmh20002
    @dmh20002 8 лет назад

    another good reason to use factories instead of instantiating concrete classes is that you can choose between factories (or parameterize them) at runtime to get different object variants without changing source code. which you would have to do if you directly instantiate a concrete class.

  • @labeebahmad1602
    @labeebahmad1602 8 лет назад

    Awesome show.

  • @surajit96
    @surajit96 7 лет назад +1

    Hi, I think this is also called module pattern. There are two versions of module pattern. If you write the talk function within the body and expose by the property {talk: talk } or simply {talk} (I did not try this!) then it is revealing module pattern or the other way around!!

    • @funfunfunction
      @funfunfunction  6 лет назад

      I thought so for a while by, no, they are not quite equivalent. I don't quite remember what the differences are, but if I had called the video revealing module pattern (which is the full name of the pattern I believe you are referring to) people would have complained that I did not implement it correctly. Thus, the "factory function" terminology.

  • @RonanConnolly
    @RonanConnolly 5 лет назад

    You rock man! Keep it up :)

  • @deepakdeep3498
    @deepakdeep3498 6 лет назад

    This is really awesome. I started learning design patterns in JavaScript. Could you teach us all the design patterns in JavaScript?

  • @djb5255
    @djb5255 8 лет назад

    I never use "this" in C#. Thanks for the insight :-)

  • @juliepanko
    @juliepanko 6 лет назад

    dude, you're amazing! :D

  • @SgtThiel
    @SgtThiel 5 лет назад

    Thank you. That seems really nice
    But doesn't that means that each instance of doggo will have its own implementation of talk, unrelated to a common prototype chain?
    Is from there that the performance loss comes from?

  • @WendtRiding
    @WendtRiding 8 лет назад +2

    Great addition to the series. I miss the plant. :(

    • @funfunfunction
      @funfunfunction  8 лет назад +1

      +Brian Wendt Me too. Hopefully I'll be back in my normal study in a couple of months (we have live-in relatives at the moments hogging it :))

  • @pjmelling
    @pjmelling 8 лет назад

    These are great! Thank you! @mpjme, what's a frame in this context?

    • @funfunfunction
      @funfunfunction  8 лет назад

      +Peter M Frame as in frames per second. If you want 60 FPS, you have a frame budget of about 16ms.

  • @HiepLe5
    @HiepLe5 8 лет назад +2

    I did not quite get the case you refered about 'this' pointing to the wrong object. Can you make a video about 'this'?

  • @jackquarry3345
    @jackquarry3345 8 лет назад

    loving the bg music XD

  • @Fred-eo4ry
    @Fred-eo4ry 4 года назад

    Hi @mpj! Thanks by the video.

  • @mr.w7803
    @mr.w7803 8 лет назад

    I noticed some similarities between the example you showed and the React.js tutorials I've been following. Could be interesting to see somethings where the syntax is compared, maybe it could include a quick overview of ES6 too :)

  • @richardmccormack2486
    @richardmccormack2486 6 лет назад

    Dude, you are the best!
    Your videos clear up so much :)
    What event if the green wristband in the vid from? :D

  • @dhanababu4361
    @dhanababu4361 8 лет назад

    You are great man :), every video linked to another video...

  • @ben-cb5er
    @ben-cb5er 3 года назад

    Hi just saw this video.. I'm just curious if you still don't prefer classes in your projects or work? Good content by the way. Thank you

  • @laeeqa310
    @laeeqa310 3 года назад

    hahahah you are so funny.... Just love the way you teach... Thank you sir...

  • @maxhay7117
    @maxhay7117 3 года назад

    But what if I needed to call dog.talk() inside the factory? Would it be best to just declare the function outside the returned object and pass it in, or is there a better way?

  • @cybermoongamer1071
    @cybermoongamer1071 5 лет назад

    How can associate a factory functions with the Singleton Design pattern? Do you have a video where you explain Singleton Design Pattern?

  • @decker6875
    @decker6875 8 лет назад

    Is it also possible writing talk with the arrow syntax getting this bind to the isntance?

    • @funfunfunction
      @funfunfunction  8 лет назад

      not with classes, no. there is a proposal for property thingees in ES7 that can do it, but ES6 arrow functions does not solve it with classes.

  • @bryannsotomayor2575
    @bryannsotomayor2575 4 года назад +1

    1:53 My favorite part of this video.

  • @jesusgonzalez-td8pd
    @jesusgonzalez-td8pd 3 года назад

    What about using self = this at the beginning of the class or factory?
    I almost always do this to get away with the closures problems
    I also prefer the factory model. But some frameworks are more into classes like TS.

  • @daveh3971
    @daveh3971 8 лет назад

    What do you think of assigning this to another property while defining a function? Such as var self = this

  • @alanlal5625
    @alanlal5625 6 лет назад

    how did you measure the performance difference between classes and factory ?

  • @tomd5678
    @tomd5678 5 лет назад

    Very good. It looks better, cleaner

  • @ANUMPA1
    @ANUMPA1 6 лет назад

    What do you mean when you say the sound variable is properly private to the dog?