No video

Factory Functions in JavaScript

  Рет қаралды 211,575

Fun Fun Function

Fun Fun Function

9 жыл бұрын

💖 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.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 KZfaq 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 KZfaq.
Content Topics revolve around: JavaScript, Functional Programming, Software Architecture, Quality Processes, Developer Career and Health, Software Development, Project Management

Пікірлер: 554
@nosajghoul
@nosajghoul 8 жыл бұрын
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 8 жыл бұрын
Kyle Simpson!
@regularwebguy6414
@regularwebguy6414 6 жыл бұрын
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. :)
@tilakmadichettitheappdeveloper
@tilakmadichettitheappdeveloper 8 жыл бұрын
Thanks for 2 reasons: 1) For learning English 2) For teaching in a simple way !
@michaelguild
@michaelguild 5 жыл бұрын
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 :)
@Adam.Garrett-Harris
@Adam.Garrett-Harris 9 жыл бұрын
Great videos! I discovered this channel last night and watched all of them!
@funfunfunction
@funfunfunction 9 жыл бұрын
+Adam Harris Wow, awesome! Welcome to the channel! :)
@vbikcl
@vbikcl 8 жыл бұрын
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 жыл бұрын
+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 жыл бұрын
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 жыл бұрын
@@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.
@lifeacoeur7037
@lifeacoeur7037 8 жыл бұрын
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 !
@softengi4043
@softengi4043 8 жыл бұрын
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.
@BrettCoffin
@BrettCoffin 9 жыл бұрын
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 !
@zackoncode1261
@zackoncode1261 4 жыл бұрын
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...
@venicebeachsurfer
@venicebeachsurfer 7 жыл бұрын
"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.
@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.
@ericromanenghi6346
@ericromanenghi6346 9 жыл бұрын
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!
@jongeduard
@jongeduard 5 жыл бұрын
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.
@scottldn
@scottldn Жыл бұрын
Still relevant, and still the best resource for breaking down JS concepts imo
@HariShekhar
@HariShekhar 5 жыл бұрын
Again a superb video. You have made factory functions so simple. Thank you
@jakewilson1070
@jakewilson1070 8 жыл бұрын
Wow how have I never stumbled across your videos before? Good stuff, informative, educating and funny :-)
@wishmaker1443
@wishmaker1443 5 жыл бұрын
"It hurts my gentle and beautiful soul to look at this code - it looks like... the shit!" - awesome! :))))
@collin_ph6023
@collin_ph6023 4 жыл бұрын
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 жыл бұрын
@@collin_ph6023 but it sound more french that way
@88Timur88Bahmudov88
@88Timur88Bahmudov88 4 жыл бұрын
@@collin_ph6023 he is not a native speaker, so he probably didn't know about it at the moment of recording the video
@SergeofBIBEK
@SergeofBIBEK 7 жыл бұрын
I'm sold. I'll be doing this instead of the prototype nightmare from now on.
@nchecker00
@nchecker00 6 жыл бұрын
whatching your vids not to learn js, but to cheer yourself up
@wishmaker1443
@wishmaker1443 5 жыл бұрын
This is an incredible description! Thank you!
@matewilk
@matewilk 9 жыл бұрын
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 9 жыл бұрын
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
@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!! 🙂
@DannyFeliz
@DannyFeliz 8 жыл бұрын
YOU CRACK ME UP at 01:53 Jaja. Really nice video video
@ThabileVatsha
@ThabileVatsha 6 жыл бұрын
hahaha dead!
@seancampbell5641
@seancampbell5641 9 жыл бұрын
Just thanks again for putting the work into these videos. Helps a lot
@Revolution3030
@Revolution3030 2 жыл бұрын
This video solves a problem I've been working on for a week with websockets
@GodOfMacro
@GodOfMacro 8 жыл бұрын
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.
@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!
@joshuavanmeer2002
@joshuavanmeer2002 8 жыл бұрын
This is awesome. Had a good grasp of this binding, but feels like this was the last missing piece of the puzzle.
@ruslansataiev9882
@ruslansataiev9882 8 жыл бұрын
As always concise, clear and useful. Thank you :)
@userJorgeCarmine
@userJorgeCarmine 6 жыл бұрын
Hi, I'm learning JavaScript and English, with your channel I can learn about both
@sawomirbudzynski8914
@sawomirbudzynski8914 5 жыл бұрын
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.
@LearnFrontendNow
@LearnFrontendNow 4 жыл бұрын
Only MPJ could make Factory Functions this fun 😂
@BigBoxRetroCollector
@BigBoxRetroCollector 5 жыл бұрын
These videos are awesome! Thanks a lot. This is the ultimate resource for a developer, and especially for front end devs.
@geocine
@geocine 7 жыл бұрын
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 жыл бұрын
+geocine thanks! I have something like that in the works.
@artgreg2296
@artgreg2296 6 жыл бұрын
on patreon you can donate www.patreon.com/funfunfunction
@exquisiteoath
@exquisiteoath 9 жыл бұрын
I think there comes a point where personal style can be allowed to enter into this. I'm a big fan of factories, but I still find plenty of times when binding makes perfect sense; even within factories. Not that I don't appreciate the value of factories, just that I would argue against the unilateral application of any approach. **EDIT** Actually, maybe you can suggest a cleaner way of thinking about something like this: engine.init = function (params) { this.targets = document.querySelectorAll(params.targetClass); Array.prototype.forEach.call(this.anchors, function (element, index, array) { this.doSomethingWithElement(element); }.bind(this)); I'd rather not have to write engine.listenAndExpand so as to ensure late binding. Engine will eventually be returned by a factory after it's been built up and then inside a consumer it can be called like: engineConsumer = factory()init({targetClass: ".myTargets"});
@ivanmatvieiev8146
@ivanmatvieiev8146 8 жыл бұрын
Best channel about JavaScript that I ever seen!
@surajit96
@surajit96 8 жыл бұрын
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.
@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.
@MrCentripetal
@MrCentripetal 8 жыл бұрын
I love your channel. You learned me so much stuff in a such simple and elegant way ! :)
@fzxtT
@fzxtT 8 жыл бұрын
Coming from an OOP background, I really appreciate the Class method better. You could always just bind each of the functions of your class in your constructor.
@funfunfunction
@funfunfunction 8 жыл бұрын
+fzxtT yes, but if you do binding in the constuctor, you're creating new function instances of them all, completely evaporating all performance benefits of the class. You're just creating something that is slower and more convoluted than the alternative for no other good reason than it feeling familiar (even though it really isn't because it's all a leaky and confusing abstraction on top of the prototype anyway)
@fzxtT
@fzxtT 8 жыл бұрын
funfunfunction guess you learn something new everyday. thanks funfunfunction.
@bogdandim
@bogdandim 8 жыл бұрын
Regarding the correct context, you could easily ensure it when you declare `talk`. Instead of: talk() { ... } you could make it: talk = () => { ... }
@HanjuKimchi
@HanjuKimchi 8 жыл бұрын
My way too
@wvvwwwvvw
@wvvwwwvvw 8 жыл бұрын
+Bogdan Dimofte I'm learning JS here and this syntax is something really wierd that I haven't seen anywhere before. What is that, if I may ask?
@bogdandim
@bogdandim 8 жыл бұрын
+Aleksandr Oleshko it's like saying `talk = function() {...}`, except the arrow is binding as described in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
@wvvwwwvvw
@wvvwwwvvw 8 жыл бұрын
+Bogdan Dimofte Arrow Functions, thats how its called. Thank you ever so much!
@brawndo8726
@brawndo8726 5 жыл бұрын
If I'm not mistaken by class syntax handling, it would need to be `const talk = () => { ... }` otherwise you would be declaring a global variable that could be overwritten, no?
@irmoathlete
@irmoathlete 8 жыл бұрын
You deserve more subs, your explanations are great. Keep up the good work.
@ianjamiesonmusic
@ianjamiesonmusic 7 жыл бұрын
Very clear, concise, accurate and informative.
@Saturdayreview98
@Saturdayreview98 Жыл бұрын
You are my life(time) saver Thank you very very much
@bryannsotomayor2575
@bryannsotomayor2575 4 жыл бұрын
1:53 My favorite part of this video.
@dacksmilliken9804
@dacksmilliken9804 7 жыл бұрын
the factory function is an example of prototypal inheritance, right? the first object we create is 'dog' with the talk method. we then create 'sniffles', which is an instance of 'dog'. when we call talk on 'sniffles', the method does not exist on 'sniffles', so the Js interpreter looks to it's prototype, which is 'dog', and there it sees the talk method, which can be called by 'sniffles'.
@brianpmorin
@brianpmorin 7 жыл бұрын
Not exactly. I think you're going wrong by saying the first object, 'dog' has a talk method. Instead, dog is a function. That function returns an object with a talk method. If you were to type out the example code and check sniffles.__proto__, you would see that sniffle's prototype is Object, not dog. Happy coding!
@MapMavericks
@MapMavericks 8 жыл бұрын
I LOVE your videos and your style. Thanks for making programming easier! CHEERS
@hyperbooldog7468
@hyperbooldog7468 6 жыл бұрын
Technically speaking, closures are not completely necessary to understand this concept. Actually, the talk method (which is the closure in sight) can be refactored to a property, assigning to it the value talk instead of a function returning it. Then, the returned object will not be nor contain a closure anymore, since object literals don't create a scope and don't need to remember the generating scope after it's popped out from the call stack, they're just values returned from functions ;-)
@ShaneCrouch
@ShaneCrouch 6 жыл бұрын
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); } }
@SoeaOu
@SoeaOu 8 жыл бұрын
now i get why new and class keyword in JS suck, thanks
@Vintharas
@Vintharas 9 жыл бұрын
Great video! Keep them coming! ^_^
@jc-depre
@jc-depre 8 жыл бұрын
great video, simple as it should be, thanks mpj
@ClemmonsX
@ClemmonsX 6 жыл бұрын
it was what I have looking for from long time :) thank you man
@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!!!!
@fhmtz
@fhmtz 9 жыл бұрын
Excellent video! Thank you!!! You're the best!
@WendtRiding
@WendtRiding 9 жыл бұрын
Great addition to the series. I miss the plant. :(
@funfunfunction
@funfunfunction 9 жыл бұрын
+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 :))
@panicogalactico7379
@panicogalactico7379 2 жыл бұрын
All you are saying is true... except that using arrow methods will solve all the problems that classes might have. Classes rule, but you need to know how to use them
@davidsaint8866
@davidsaint8866 5 жыл бұрын
LMAOOOO!!!! 2:08 made me subscribe, turn on notifications and like this video.
@HiepLe5
@HiepLe5 8 жыл бұрын
I did not quite get the case you refered about 'this' pointing to the wrong object. Can you make a video about 'this'?
@surajit96
@surajit96 8 жыл бұрын
By the way, I watched lot of your videos lately and totally loved them!!
@grancubodemierda
@grancubodemierda 8 жыл бұрын
Even if you want flightweight objects, you still can avoid classes, and do what was done before ES6: creating a prototype with the common code, and then create an object with local data bound to that prototype (which is what happens when the code is compiled to ES5 hehe). However, you get what you call the banana-gorilla problem :)
@abhichaurasia7054
@abhichaurasia7054 6 жыл бұрын
That expression at 4:49. I couldn't stop bursting out laughing
@ZawWinnHlaing
@ZawWinnHlaing 9 жыл бұрын
it's a great series and thanks you for sharing @mpjme. i'm stay curious :D
@cintron3d
@cintron3d 6 жыл бұрын
Anyone else notice that dot in the video? I thought it was on my screen at first - then I thought it was a dead-pixel - then I realized it's actually part of the video.
@tadeoriverosk
@tadeoriverosk 8 жыл бұрын
You're a great guy! Thanks so much for doing this!
@jbcrestot
@jbcrestot 7 жыл бұрын
hey @funfunfunction, I really appreciate this video and be convinced by factories. I'd like to spread this new way of creating object to my coworker, but I can't find out how functions can call each other. For example : return { talk: () => console.log(sound), callMaster: () => { talk() talk() } } talk will be undefined just as this.talk() Maybe I'm missing something basic. In hope, you'll answer. :/
@funfunfunction
@funfunfunction 7 жыл бұрын
+Sulfa just assign talk to a variable before assigning it to the object.
@jbcrestot
@jbcrestot 7 жыл бұрын
ok, that's simple. Thank you very much for responding. :)
@tomd5678
@tomd5678 5 жыл бұрын
Very good. It looks better, cleaner
@wodemoshou
@wodemoshou 8 жыл бұрын
This is awesome! Thanks for sharing and teaching!
@tenstairs
@tenstairs 5 жыл бұрын
So good! I wish I started watching your videos years ago. Better late than never though
@laeeqa310
@laeeqa310 3 жыл бұрын
hahahah you are so funny.... Just love the way you teach... Thank you sir...
@Mohammad-wo7yi
@Mohammad-wo7yi 9 жыл бұрын
In terms of memory consumption, I think (but I'm not sure) that the syntax Dog.prototype.talk = function () { //blah blah } // or The new ECMA2015 class syntax are more efficient, because they create one reference to the function in memory, where the factory function creates a new reference to the talk() function every time we create a new object.
@funfunfunction
@funfunfunction 9 жыл бұрын
+Mohammad Elbanna Yes, I talk about that in the video. There is a small performance difference that will start to matter if you are creating a lot of objects (approaching 60000 per second). If you're just creating a couple of thousand per second it's completely irrelevant to you performance and you are spending you limited time hunting an innocent suspect of you're having performance issues in your app.
@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!
@Fred-eo4ry
@Fred-eo4ry 4 жыл бұрын
Hi @mpj! Thanks by the video.
@eidiazcas
@eidiazcas 2 жыл бұрын
factories eat more space as well so it hits performance in both ways when there are too many objects
@yomasanamae5433
@yomasanamae5433 6 жыл бұрын
great episode this is too! i’m watching this series and try it one by one.
@baharmand
@baharmand 8 жыл бұрын
Very informative, thanks for the clear explanations.
@gerardgauthier4876
@gerardgauthier4876 5 жыл бұрын
Factories also let the programmer freeze the object when its created. Classes are also great for creating namespaces around data and functions.
@mileswarburton9676
@mileswarburton9676 8 жыл бұрын
Great videos, I really like your method of teaching.
@diwu183
@diwu183 8 жыл бұрын
Really nice! Thanks for sharing about this!
@wagnermoreira786
@wagnermoreira786 5 жыл бұрын
awesome explanation!
@kevincarr2334
@kevincarr2334 7 жыл бұрын
Thank you this was a great and educational 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
@deepakdeep3498
@deepakdeep3498 6 жыл бұрын
This is really awesome. I started learning design patterns in JavaScript. Could you teach us all the design patterns in JavaScript?
@peterhayman
@peterhayman 5 жыл бұрын
this video changed how i see javascript
@DmitriZaitsev
@DmitriZaitsev 7 жыл бұрын
The factory example here is not quite equivalent to the class, because it creates a new closure for every object, so it can be argued to consume more memory. To use prototypes instead, you need to do something like that: const dog = sound => { const methods = { talk: () => console.log(sound) } return () => Object.create(methods) } Besides, this factory also has the nice advantage of being more reusable as the sound is not hardcoded anymore.
@malo.widerspach
@malo.widerspach 6 жыл бұрын
js classes can be useful with the "extends" keyword, to add methods to core classes, replacing prototype :) but otherwise they are mainly a marketing tool for people coming from oop languages
@kyle-rb
@kyle-rb 6 жыл бұрын
I feel like trying to add an object method as an event listener is something that you would only do if you fundamentally lacked understanding of how JavaScript functions and objects work. And if the 'talk' method actually had arguments, then you would notice the error much more easily; unless the method specifically accepted a single event argument, you might stop for a minute and think about why passing an object method as an event callback is a problem with your code, and not a problem with JS's this-binding.
@ZoroastrianCowboy
@ZoroastrianCowboy 3 жыл бұрын
Please explain the underscore in the arrow function you passed to .click() _ => sniffles.task() what is the underscore before the fat arrow do??
@AlexQuirk
@AlexQuirk 8 жыл бұрын
Really great stuff, good work
@FrancoisvanderMerwe
@FrancoisvanderMerwe 8 жыл бұрын
I am getting super confused by the fact that you are using ECMAScript 6!! Is this type of factory the same as the factories in AngularJS same concept? Loving the videos by the way! Thumbs up!
@funfunfunction
@funfunfunction 8 жыл бұрын
Confusion is your friend, it means you're learning. No, Angular factories is just weird and overly complicated, like Angular in general.
@asherrfacee
@asherrfacee 8 жыл бұрын
What category does using prototype inheritance fall into, and why wouldn't you use it over either of your examples shown? The way I learned to make object in javascript was: function dog() { this.sound = "woof"; } dog.prototype.talk = function() { console.log(this.sound); } var sniffles = new dog(); sniffles.talk(); If I wanted to make the 'sound' variable private I could do that with this solution as well.
@OhadS
@OhadS 8 жыл бұрын
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. 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 жыл бұрын
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) } }
@ekaterinahorton768
@ekaterinahorton768 4 жыл бұрын
Great clear video, thank you very much! Subscribed :)
@leftover7766
@leftover7766 6 жыл бұрын
At the end of this special movie, it would've been cool if you had slapped them up side by side to commit the difference code wise between a class and factory to memory. Other than that, I give your presentation 5 Yaba Daba Dooos!! (the most possible Yaba Daba Dooos)
@NidraxGaming
@NidraxGaming 4 жыл бұрын
class Dog { private const _sound = "woof"; public void Talk() { Console.WriteLine(_sound); } public static Dog Sniffles { get { return new Dog(); } } } btn.click += Dog.Sniffles.Talk; Idk, I find it more elegant than factory functions.
@uclastudentservices309
@uclastudentservices309 6 жыл бұрын
Another very good tutorial! Thank you!
@RickonDraw
@RickonDraw 7 жыл бұрын
Instead of binding this outside the class at the click handler, can you not also bind this inside the class constructor? Would that be a better option (if you are using classes instead of factories, because reasons)? Like so: constructor() ... this.talk = this.talk.bind(this)
@funfunfunction
@funfunfunction 7 жыл бұрын
+Rick Lancee you can. There are two problems with the approach though. The first one is that you are adding a sort of leaky abstraction in the sense that while you are trying to make it easier for the developer calling the class, they now have to know the insides of your class, to know that you are doing work for them. The second problem is that bind creates a new function, which is exactly what the factory function does. You're effectively throwing away the only performance/memory benefit the class has, and you are then better off just using factory functions because they are much simpler and lacks the quirks of the class.
@RickonDraw
@RickonDraw 7 жыл бұрын
funfunfunction aaaha! thanks for explaining that so clearly. I was taught this trick by fellow developer, but now i see that it might not be such a good idea. Thanks!
@labeebahmad1602
@labeebahmad1602 8 жыл бұрын
Awesome show.
@santosharakere
@santosharakere 8 жыл бұрын
Great video. Thank you.
@patriklindahl4991
@patriklindahl4991 9 жыл бұрын
Nice video! Just a couple of comments... Apart from the slight performance boost I also think that instanciating a class (prototype functions) takes less memory because only one copy of each function is held in memory. There is also another this pointer technique that could be used. Probably not the nicest one but you could do a "private" variable in the top of the "class" called for example that (var that = this;) and use that instead of this. If that makes sense :)
@funfunfunction
@funfunfunction 9 жыл бұрын
There is lots of convoluted ways to deal with it, yes. But unless you actually need the performance and memory profile of classes, you are just wasting yours and your colleagues time on premature optimization. If you really need a class, by all means, use it - but if you don't, a factory function is so much nicer and easier.
@patriklindahl4991
@patriklindahl4991 9 жыл бұрын
True
Composition over Inheritance
8:34
Fun Fun Function
Рет қаралды 510 М.
Prototypes in JavaScript - FunFunFunction #16
11:56
Fun Fun Function
Рет қаралды 123 М.
If Barbie came to life! 💝
00:37
Meow-some! Reacts
Рет қаралды 50 МЛН
What is Factory Function in JavaScript? - JS Tutorial
17:31
ColorCode
Рет қаралды 57 М.
STOP Using Classes In JavaScript | Prime Reacts
14:02
ThePrimeTime
Рет қаралды 231 М.
The purest coding style, where bugs are near impossible
10:25
Coderized
Рет қаралды 946 М.
Looking Under the Hood of JavaScript
6:34
ThePrimeagen
Рет қаралды 181 М.
bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
15:39
Javascript Design Patterns #1 - Factory Pattern
10:12
DevSage
Рет қаралды 160 М.
var, let and const - What, why and how - ES6 JavaScript Features
19:19
Fun Fun Function
Рет қаралды 180 М.
Higher Order Functions in JavaScript Explained Simply
9:55
Teddy Smith
Рет қаралды 7 М.
If Barbie came to life! 💝
00:37
Meow-some! Reacts
Рет қаралды 50 МЛН