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 Наука
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.
Kyle Simpson!
Ha ha Javascript Sesame Street
This just made me burst out loud !!!! lol
That is just as funny as the guy on the video. Thanks for the laugh. :)
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 :)
unfortunately the stopped producing content for a full time job. What a shame.
@@carminetambascia6355 I thought she quit coding all together to just chill. Pretty sure he's making good passive income at this point :)
Thanks for 2 reasons:
1) For learning English
2) For teaching in a simple way !
Great videos! I discovered this channel last night and watched all of them!
+Adam Harris Wow, awesome! Welcome to the channel! :)
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!
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.
+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.
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.
@@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.
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!! 🙂
Again a superb video. You have made factory functions so simple. Thank you
This is an incredible description! Thank you!
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...
Just thanks again for putting the work into these videos. Helps a lot
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 !
As always concise, clear and useful. Thank you :)
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.
Excellent video! Thank you!!! You're the best!
I love your channel. You learned me so much stuff in a such simple and elegant way ! :)
I LOVE your videos and your style. Thanks for making programming easier!
CHEERS
You deserve more subs, your explanations are great. Keep up the good work.
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.
These videos are awesome! Thanks a lot. This is the ultimate resource for a developer, and especially for front end devs.
This is awesome! Thanks for sharing and teaching!
"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.
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 !
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.
You're a great guy! Thanks so much for doing this!
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!
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!!!!
Very clear, concise, accurate and informative.
Wow how have I never stumbled across your videos before? Good stuff, informative, educating and funny :-)
great video, simple as it should be, thanks mpj
Really nice! Thanks for sharing about this!
This is awesome. Had a good grasp of this binding, but feels like this was the last missing piece of the puzzle.
Very informative, thanks for the clear explanations.
just discovered your channel. amazing! thank you!
+Kiran Randhawa thanks for tuning in, Koran! Glad to have you here!
Great videos, I really like your method of teaching.
it's a great series and thanks you for sharing @mpjme. i'm stay curious :D
Best channel about JavaScript that I ever seen!
whatching your vids not to learn js, but to cheer yourself up
Hi, I'm learning JavaScript and English, with your channel I can learn about both
it was what I have looking for from long time :) thank you man
YOU CRACK ME UP at 01:53 Jaja.
Really nice video video
hahaha dead!
Another very good tutorial! Thank you!
Still relevant, and still the best resource for breaking down JS concepts imo
Great clear video, thank you very much! Subscribed :)
Thank you this was a great and educational video!
By the way, I watched lot of your videos lately and totally loved them!!
Really great stuff, good work
So good! I wish I started watching your videos years ago. Better late than never though
Great video. Thank you.
This video solves a problem I've been working on for a week with websockets
I'm sold. I'll be doing this instead of the prototype nightmare from now on.
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);
}
}
great job as always !!
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.
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.
great episode this is too! i’m watching this series and try it one by one.
Great video! Keep them coming! ^_^
Wonderful channel congratzzz!!
+Webschool - JavaScript thanks a lot for your kind words. :)
Only MPJ could make Factory Functions this fun 😂
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.
+geocine thanks! I have something like that in the works.
on patreon you can donate www.patreon.com/funfunfunction
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 ?
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
awesome explanation!
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
You are my life(time) saver
Thank you very very much
cool. thank you a lot for the explanation!
LMAOOOO!!!! 2:08 made me subscribe, turn on notifications and like this video.
"It hurts my gentle and beautiful soul to look at this code - it looks like... the shit!" - awesome! :))))
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.
@@collin_ph6023 but it sound more french that way
@@collin_ph6023 he is not a native speaker, so he probably didn't know about it at the moment of recording the video
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?
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.
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)
}
}
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
@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?
+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.
Awesome video. really nice!
I love this channel. 😄
Great video, thanks Dude.
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.
Awesome show.
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!!
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.
You rock man! Keep it up :)
This is really awesome. I started learning design patterns in JavaScript. Could you teach us all the design patterns in JavaScript?
I never use "this" in C#. Thanks for the insight :-)
dude, you're amazing! :D
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?
Great addition to the series. I miss the plant. :(
+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 :))
These are great! Thank you! @mpjme, what's a frame in this context?
+Peter M Frame as in frames per second. If you want 60 FPS, you have a frame budget of about 16ms.
I did not quite get the case you refered about 'this' pointing to the wrong object. Can you make a video about 'this'?
loving the bg music XD
Hi @mpj! Thanks by the video.
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 :)
Dude, you are the best!
Your videos clear up so much :)
What event if the green wristband in the vid from? :D
You are great man :), every video linked to another video...
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
hahahah you are so funny.... Just love the way you teach... Thank you sir...
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?
How can associate a factory functions with the Singleton Design pattern? Do you have a video where you explain Singleton Design Pattern?
Is it also possible writing talk with the arrow syntax getting this bind to the isntance?
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.
1:53 My favorite part of this video.
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.
What do you think of assigning this to another property while defining a function? Such as var self = this
how did you measure the performance difference between classes and factory ?
Very good. It looks better, cleaner
What do you mean when you say the sound variable is properly private to the dog?