Factory Function vs. Constructor vs. Class - JavaScript Tutorial

Поделиться
HTML-код
  • Опубликовано: 23 янв 2025

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

  • @ColorCode-io
    @ColorCode-io  3 года назад +24

    What is the difference between a Factory Function and a Constructor in JavaScript?

    • @kran399
      @kran399 3 года назад +1

      Factory Functions are Better More Secure than Constructor Functions.

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

      @@kran399 can you proof this ?

    • @mohammadyaseen5339
      @mohammadyaseen5339 3 года назад +1

      i think the onlu difference is that you can add/modify method using "constructrorname.prototype.newfunction" in constructor function but you cannot do this in factory function.

    • @jameslogan6626
      @jameslogan6626 2 года назад +1

      Constructors are OOP. Anyone saying otherwise is simply wrong and abusing standard nomenclature.

    • @caribbeanman3379
      @caribbeanman3379 2 года назад +2

      A factory function basically clones new copies of all object members defined in the object, in each object instance that is created - by default; whereas a constructor function only clones the members defined in the constructor.
      Lately I've been using an OOP framework that uses a singleton object as a class that contains only static methods. One of those static methods serves as a factory function for creating data objects that the class object can then manipulate. Static functions serve as prototypal functions by having a data object passed to it as an argument. So instead of using the traditional this keyword to reference instance objects, you use the instance argument passed. For example:
      let ClassObj = Object.create(null);
      ClassObj.newDataInstance = function(arg1, arg2) {
      return {
      property1: arg1,
      property2: arg2
      };
      };
      ClassObj.setArg1 = function(instance, newArg1) {
      instance.arg1 = newArg1;
      };
      But it can get a bit tiresome to always have to pass in an instance argument every time you want to work with instance data. So I've also toyed with the idea of having a static defaultIntance property in the Object so that when there is a series of consecutive calls involving the same instance you can use a function like this:
      ClassObj.withInstance = function(instance) {
      ClassObj.defaultInstance = instance;
      };
      to initially lock on to a particular instance that will be used for the following instance calls without having to repeatedly enter an instance argument for each call. Now the setArg1 function would look like this:
      ClassObj.setArg1 = function(newArg1, instance = ClassObj.defaultyInstance || null) {
      instance.arg1 = newArg1;
      };

  • @dreamer4515
    @dreamer4515 Год назад +23

    The best decision in my RUclips History was to subscribe to this Guy. His teaching method is just amazing. You should launch your own complete js course, why limit it to 20?😅

  • @flavour_country
    @flavour_country 2 года назад +23

    Hands down the best teacher I’ve come across on RUclips. Keep producing content!!! Love it

    • @ColorCode-io
      @ColorCode-io  2 года назад +1

      Thank you

    • @umcode
      @umcode Год назад +2

      Why you are not active 😢😢the bestest teacher ever

  • @SiRexable
    @SiRexable 2 года назад +23

    underrated channel! I'm watching 10 Things JS Developers Should Know and I'm loving it, you explain everything in such great detail and with nice humor too. TOP NOTCH QUALITY VIDEOS HERE. Keep it going man, I hope this channel gets more subs.

  • @asheradanehi
    @asheradanehi Год назад +3

    I'm happy I found your Javascript videos. Saying a very appreciating thank you from Northern Nigeria for now.

  • @bmehder
    @bmehder 2 года назад +3

    This is the first video I have seen from this channel. Subscribed.

  • @KuramasaXP
    @KuramasaXP 7 месяцев назад +2

    Following the Odin Project and looking up your videos definitely saves time on certain topics. Very clear and concise

  • @sara5490
    @sara5490 2 года назад +9

    So funny, love how he doesn't just explain how to create constructors/functions but also gives practical examples of how and why the distinctions are important. Liked and subscribed.

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

    Thank you so much for this series of videos! You explanations are perfectly clear, the editing is amazing and they are super entertaining :)

  • @iamseanhahaha
    @iamseanhahaha 3 года назад +11

    Love the flow of this video. Awesome editing work as well. You deserve more subs!! (Here before 6K 😎)

  • @FrostDrive
    @FrostDrive 2 года назад +6

    Wow, I've watched so many videos on this and your explanation is by far the best. deserve way more subs

  • @zafiroula100
    @zafiroula100 2 года назад +2

    You explained the difference so good! I was struggling to understand the difference since im new to JS. You're the best🙌

  • @shubhamjangid7012
    @shubhamjangid7012 Год назад +2

    The presentation is engaging, and the information provided is very valuable. The production quality is top-notch, and it's evident that a lot of effort went into creating this content. Keep up the great work!

  • @thomaswinterburn6680
    @thomaswinterburn6680 Год назад +2

    Thanks for this tutorial series
    My key Takeaways from this video
    Factory functions, by default, create distinct copies of methods for each object, which can be memory intensive.
    Constructors, by using prototypes, share a single method instance among all objects, which is memory efficient.
    Constructors enable genuine inheritance, unlike factories that need workarounds for a similar effect.
    Why Use Factories:
    Simplicity: They're just standard functions without needing the 'new' keyword or dealing with 'this'.
    Flexibility: They leverage closures, promoting data privacy by not exposing certain properties or methods directly.
    Data Privacy: Properties or methods can be hidden, reducing the chance of unintentional overwrites.

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

    i am usually not commenting but once i saw it has only 25k views i had to come down here and say i've been struggling with these stuff for a while and this series shed light over everything
    i really hope more programmers get to see these :D

  • @TheAcidMotion
    @TheAcidMotion 3 года назад +5

    Great coverage of the topic and parallels of theory against real-world examples. True scholar and a gentleman in real life, keep it up.

  • @stephenreynolds0220
    @stephenreynolds0220 3 года назад +2

    I am currently doing a project for college on constructor functions, and these videos have helped a lot! You are the most clear and concise person to explain all of the parameters of a constructor function. Thank you! :D

  • @rjwhite4424
    @rjwhite4424 2 месяца назад +1

    Why doesn’t this series have millions of views

    • @ColorCode-io
      @ColorCode-io  2 месяца назад

      Every view counts 🙏 ♥️

  • @gustavo.paixao
    @gustavo.paixao 3 года назад +4

    I've never watched a video of yours before, but way to go. Funny, simple and accurate. Good job!

  • @gottadance220
    @gottadance220 10 месяцев назад

    As someone who wants to work as a developer relations engineer, I love this channel. So informative and so fun! Hope I can make great content like this some day. Very inspiring

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

    Agreed with the other comments. Underrated channel - you have a new subscriber. Not only do you explain concepts in a clear and concise way but you explain WHY IT MATTERS. And you're engaging. You should have at least 400k-500k subscribers.

  • @chhavimanichoubey9437
    @chhavimanichoubey9437 2 года назад +1

    hugely underrated quality channel

  • @andreadipasquale1593
    @andreadipasquale1593 10 месяцев назад

    Grazie Mille per i tuoi video, finally I found someone who knows how to make people understand these tricky things. Bravo , Complimenti davvero! Se vieni in Italia your next espresso is on me!

  • @kunnudev7250
    @kunnudev7250 2 года назад +1

    Very underrated channel don't worry will get 1 billion+ subscribers bro thanks bro great job

  • @BigSmoke-r9w
    @BigSmoke-r9w 6 месяцев назад

    I came back to this video just to refresh my mind! Thank you once again!

  • @DevOpsDirective
    @DevOpsDirective 3 года назад +3

    Just stumbled across your channel... really enjoyed this style of teaching! Great stuff!

  • @Symphetix
    @Symphetix 2 года назад +1

    Excellent. Very underrated channel!

  • @stratboy2
    @stratboy2 10 месяцев назад +1

    You speak a really good english, you explain better than most of the teacher out there, your mind is brilliant, you stand out. So thank you. What's your name and where are you from?

  • @AlejandroGarcia-ff5bz
    @AlejandroGarcia-ff5bz 3 года назад +4

    I just wanted to add a comment about using Object.Create in your factory functions like you have on 12:10. The "name" property will be added to the object you are returning, but if someone wants to loop through an object like the one in your example using a for in loop, Object.keys, Object.values, or Object.entries, they will get back an empty array. To make the object iterable they will need to add "enumerable: true" property to the "name" property. After that you can loop through the object with a for in loop or convert the keys, values, or both.

    • @ColorCode-io
      @ColorCode-io  3 года назад +3

      Good point. We're really touching on the basics here and not going super deep in any object API, but you are correct in saying you can configure your object further when you use Object.create. Thanks for the call out.

    • @AlejandroGarcia-ff5bz
      @AlejandroGarcia-ff5bz 3 года назад +3

      @@ColorCode-io No worries! It was a thing that got me once. I love your videos btw. Really well produced and easy to follow along and understand. Keep going!

  • @naveedharri
    @naveedharri 3 года назад +3

    I really had no idea, thanks alot!

  • @seanfinegan1076
    @seanfinegan1076 3 года назад +1

    Thanks for sharing. As someone learning javascript, you cleared up some confusion.

  • @lost-mar-ble
    @lost-mar-ble Год назад

    Great series. Nice to know about Eric Elliot as well.

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

    I'm liking your channel honestly

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

    10 Things JS Developers Should Know. Unfortunately I'm one of that JS developer😅.
    Under rated channel with lot of information. you deserve more subscriber sir.
    Please do more videos

  • @bigjimtrucker6042
    @bigjimtrucker6042 9 месяцев назад

    You a great Teacher and I appreciate you

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

    Top Tutorial! Greetz from Germany!!!

  • @richardradcliffe6178
    @richardradcliffe6178 2 года назад +1

    This is a banger video. Thank you for the help.

  • @elusariosinnombre2058
    @elusariosinnombre2058 3 года назад +5

    Super good production on the video. Really aids in visualizing the workings of the code! The intro music might be mixed a little too loud though.

  • @VaibhavSharma-zj4gk
    @VaibhavSharma-zj4gk 2 года назад +1

    Top quality content. 10/10.

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

    Nice style of teaching ❤

  • @deepanshukacher1536
    @deepanshukacher1536 3 года назад +1

    Really love your explanation

  • @eumm11
    @eumm11 2 года назад +1

    thank you so much, top notch explanation, amazing!!

  • @maverick-n6x
    @maverick-n6x Год назад

    very understandable and practical way explaination. thank you so much x 10

  • @kran399
    @kran399 3 года назад +1

    great Content Love from India Sir.

  • @rabiaabbas262
    @rabiaabbas262 3 года назад +1

    Really good explanation, thanks a lot!

  • @garrettg5313
    @garrettg5313 3 года назад +2

    Great video! I've been struggling for a while using The Odin Project to try to figure out what Eliott was saying in '3 types of prototypal inheritance'. Maybe you could make some videos covering some of the more confusing stuff in The Odin Project? Thanks for the help very clear.

  • @jatilyadav4000
    @jatilyadav4000 2 года назад +1

    Amazing video.. Hats off

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

    Thanks for your explanatory examples and efforts !!

  • @kitestance
    @kitestance 2 года назад +1

    Great teaching. Thank you.

  • @hannahp642
    @hannahp642 2 года назад +1

    great quality!

  • @dr.d3600
    @dr.d3600 2 года назад +1

    Great video ❤

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

    thanks for the tips. good stuff

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

    Amazing video helped a lot

  • @דניאלעורקבי
    @דניאלעורקבי 3 года назад +1

    god bless you
    you make the best videos all over the internet thank you very much
    you are the best!!!!!!

  • @ajminpradhan1112
    @ajminpradhan1112 3 года назад +1

    Extensively Underrated Channel. I am feeling lucky to see your teaching style. BTW, would love to have a youtube live collaboration with Hitesh Choudhury? 😊

    • @ColorCode-io
      @ColorCode-io  3 года назад

      Thank you. Not sure who that is but maybe in the future

  • @programadordelassombras
    @programadordelassombras 5 месяцев назад +1

    For JavaScript, Prototypical inheritance is quicker to write, less typing in my opinion. The end goal is the same: to organize, and encapsulate properties and methods that can be reused in other areas of your code. It's important to understand so you know why all objects have a toString method in JS and the behavior of Object.keys vs Object.getOwnPropertiesOf etc... If you get confused, just remember, the purpose is to have access to all of the properties and methods that are in an already defined object without having to rewrite code.

  • @Aaron-sy5yx
    @Aaron-sy5yx 3 года назад +1

    Dude great video.

  • @fizruk7644
    @fizruk7644 3 года назад +1

    Can we say that, when we define properties inside constructor functions with this keyword, it is not in prototype and it actually same thing as factory function and has same problems? And can we say that everything we write inside classes are created directly in prototype? so classes are short way of costructor.prototype ?

    • @ColorCode-io
      @ColorCode-io  3 года назад

      Almost. Adding properties to 'this' keyword in a constructor function does NOT add it to the prototype but you can reference the 'this' inside any function you add to your prototype. So they are aware of each other and that's a big advantage.
      The second part of your question is correct. Adding 'functions' to a class is the exact same thing as adding a function to the prototype of a constructor function. It's just a different syntax.

  • @derpstarz
    @derpstarz 3 года назад +1

    Good stuff! subscribed

  • @abelemmanuel4394
    @abelemmanuel4394 7 месяцев назад

    Thank u sir for the free course, I really appreciate
    But is there any way I can access the code for other courses?. i only accessed the code for episode 1, which name is the inheritance and others can't be found.

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

    very concise and informative video, can you make videos where you can explain different built-in properties in js like for object, array, set, map, dom properties.

  • @eyesoap4536
    @eyesoap4536 2 года назад +1

    Hello. Thanks for the video. What IDE are you using?

  • @ajxtc2
    @ajxtc2 3 года назад +5

    I did the same thing with constructor function as you did with factory function, the private name thing and it works the same. Just don't declare this.name and use $ {name}. idk if it's a mistake or you meant something else. great vids tho.

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

    What is this interpreter you are using for code.

  • @Chris2phaBrown
    @Chris2phaBrown 3 года назад +1

    happy to have inspired :)

  • @ebcoutinho
    @ebcoutinho 11 месяцев назад

    Pure gold found here

  • @zenreefer7817
    @zenreefer7817 3 года назад +1

    This channel is a fucking GEM

  • @michelironside6160
    @michelironside6160 3 года назад +1

    how much css and html do i need start learn javascript?

    • @ColorCode-io
      @ColorCode-io  3 года назад +2

      Zero :)

    • @AlejandroGarcia-ff5bz
      @AlejandroGarcia-ff5bz 3 года назад +1

      Technically you can start without it but eventually you will cross paths and have to learn it to go further. You can learn the fundamentals of programing using Javascript.

  • @anonlegion9096
    @anonlegion9096 2 года назад +1

    Holy shit... thank you! I now know how to create static variables/methods in my factory function! PROTOTYPES!!!!

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

    What's that awesome code editor you're using to see your objects?

  • @spidysense7754
    @spidysense7754 2 месяца назад +2

    You are soooo gooood❤❤❤

  • @LeetCodeSimplified
    @LeetCodeSimplified 3 года назад +1

    Great video, thx a lot!!

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

    By far the best explanation I've heard about this, ColorCode >>> ChatGPT

  • @cedkirdes6108
    @cedkirdes6108 3 года назад +1

    Really nice video. I was not really aware of the meaning of prototype and now its clear. Actually I'm doing some canvas / webgl animation, is it better to use classes if I need to create a lot of object with methods ?

    • @ColorCode-io
      @ColorCode-io  3 года назад

      You can definitely use classes, constructors or factories. In the end it's up to you what makes more sense to you for your particular case.

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

    i love you video, can you tell me what app or tools your using to record? it seems its cool

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

    Are factory functions more in use in the industry currently? I have seen some current online articles discussing factory & constructor functions but it also said you will rarely use them as classes are the current thing. Some of the most well known bootcamps only teach classes, while others say the classes have fallen out of favor. So it seems like it's a preference thing and probably depends on the company.

  • @jimfoley2690
    @jimfoley2690 3 года назад +1

    Great stuff

  • @miedsekadse7136
    @miedsekadse7136 2 года назад +1

    Great video

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

    Awesome.... !!! 👍

  • @12nov83
    @12nov83 Год назад

    which editor...you used? please

    • @ColorCode-io
      @ColorCode-io  Год назад

      It's called RunJS: runjs.app/?via=colorcode

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

    Liked and subscribed.

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

    14:13 Gramma song?

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

    Hi is it possible to chain factory function methods when you call them? E.g. sayName().location().favFoods().
    Not sure if I'm phrasing my question correctly sorry lol
    I can't use the `return this` keyword inside the factory function like how you would with a constructor :(
    code below:
    const Nerd = (name, city, food) => {
    const { sayName, location } = Person(name, city)
    const { favFoods } = FaveFood(food, name)
    const doSomethingNerdy = () => console.log(`${name} likes nerd stuff!`)
    return { sayName, location, favFoods, doSomethingNerdy }
    return this
    }
    const colorCode = Nerd('ColorCode', 'The Matrix', 'Fried Tofu and Teriyaki Chicken')
    colorCode.sayName().location().favFoods() // uncaught reference error :(

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

    I use simple factory functions 99% of the time, and in the 1% of times I need a complex object with inheritance, I use a prototype object with a factory function. Those also tend to be the only time I ever use the this keyword.

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

      This comment was a brain saver for me. It's been messing with my head cos I've seen examples where the returned objects of factory functions are used as parent objects for the returned objects of another Factory functions and it just messes with my head.
      Using object.create with factory functions just seems like an easier way to handle inheritance unless it has to deal with private variables.
      Am I off track here?

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

      @@dougdoug9223 now I wonder if it’s possible to use the factory function and prototype object pattern with private variables. I haven’t had any need for that yet but I’m sure it can be done, even if it might be one of those things where even if you could maybe you shouldn’t. 😄

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

    This man makes me wanna drink water whenever he does it =))

  • @mohammadyaseen5339
    @mohammadyaseen5339 3 года назад +1

    I have watched this video more than 10 time but i cannot understand the major difference between these two. Also please make a video on why we use these both for creating object i mean we can simply create objects. please make fully explained each and everything in a video abut these . I will be very thank full

  • @Dimy111
    @Dimy111 3 года назад +1

    Good vid

  • @maciekdzikdrums
    @maciekdzikdrums 8 месяцев назад

    king

  • @michamarkiewicz5355
    @michamarkiewicz5355 7 месяцев назад

    thank you

  • @matinmarzban3430
    @matinmarzban3430 6 месяцев назад

    I loved how you just put you.name= قلی
    I found that funny 😆

  • @kran399
    @kran399 3 года назад +1

    Explain " return " in JavaScript . please make a Deep UnderStanding Video ,Please Sir.

  • @Solo_playz
    @Solo_playz 2 года назад +2

    We want set up tour..

    • @ColorCode-io
      @ColorCode-io  2 года назад +1

      It’ll be included in my JS MasterClass. Coming soon.

    • @Solo_playz
      @Solo_playz 2 года назад +1

      @@ColorCode-io kk sir, we are curious about your js master classes .
      New subscriber 😊✌️

  • @GBlunted
    @GBlunted Год назад +2

    Why don't the sound work?!! Noooooo! I need this knowledge...😢😢😢

  • @aburaihan-py4vi
    @aburaihan-py4vi 3 года назад +1

    Wow!

  • @zahraBatenin
    @zahraBatenin 5 месяцев назад

    I wish he would launch a RUclips series on React.
    Wouldn't that be great :) ?

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

    okkk those who are confused see..............
    Difference is initially in factory fn -> me.__proto__ === createPerson.prototype // false.
    but in constructor fn -> ben.__proto__ === Person.prototype //true
    so in constructor fn when we create the obj with new keyword it gets the fn in its proto,
    and for factory fn we have to do it manually......

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

    OMG, have my babies; you've shown me the light with your incredible teachings!! 🤡

  • @spacey6960
    @spacey6960 5 месяцев назад

    14:08 "peeeeeerry"

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

    i like it

  • @davidmmadden
    @davidmmadden 3 года назад +1

    OG Batman