Factory Function vs. Constructor vs. Class - JavaScript Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 17 ม.ค. 2025

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

  • @ColorCode-io
    @ColorCode-io  3 ปีที่แล้ว +23

    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 TH-cam 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 TH-cam. 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.

  • @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.

    • @ColorCode-io
      @ColorCode-io  2 ปีที่แล้ว

      Awesome! Glad you liked it :)

  • @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

  • @iamseanhahaha
    @iamseanhahaha 3 ปีที่แล้ว +11

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

  • @elielberra2867
    @elielberra2867 11 หลายเดือนก่อน +1

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

  • @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.

  • @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

  • @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.

  • @rjwhite4424
    @rjwhite4424 2 หลายเดือนก่อน +1

    Why doesn’t this series have millions of views

    • @ColorCode-io
      @ColorCode-io  2 หลายเดือนก่อน

      Every view counts 🙏 ♥️

  • @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

  • @chhavimanichoubey9437
    @chhavimanichoubey9437 2 ปีที่แล้ว +1

    hugely underrated quality channel

  • @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!

  • @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!

  • @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

  • @gottadance220
    @gottadance220 9 หลายเดือนก่อน

    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.

  • @BigSmoke-r9w
    @BigSmoke-r9w 5 หลายเดือนก่อน

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

    • @ColorCode-io
      @ColorCode-io  5 หลายเดือนก่อน

      You are so welcome!

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

    I really had no idea, thanks alot!

  • @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!

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

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

    • @ColorCode-io
      @ColorCode-io  3 ปีที่แล้ว

      Wonderful to hear. Thank you.

  • @Symphetix
    @Symphetix 2 ปีที่แล้ว +1

    Excellent. Very underrated channel!

  • @kunnudev7250
    @kunnudev7250 2 ปีที่แล้ว +1

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

  • @AlejandroGarcia-ff5bz
    @AlejandroGarcia-ff5bz 3 ปีที่แล้ว +3

    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 ปีที่แล้ว +2

      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!

  • @seanfinegan1076
    @seanfinegan1076 3 ปีที่แล้ว +1

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

    • @ColorCode-io
      @ColorCode-io  3 ปีที่แล้ว

      Love to hear that, thank you

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

    I'm liking your channel honestly

  • @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?

  • @lost-mar-ble
    @lost-mar-ble ปีที่แล้ว

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

  • @bigjimtrucker6042
    @bigjimtrucker6042 8 หลายเดือนก่อน

    You a great Teacher and I appreciate you

  • @eumm11
    @eumm11 2 ปีที่แล้ว +1

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

  • @deepanshukacher1536
    @deepanshukacher1536 3 ปีที่แล้ว +1

    Really love your explanation

  • @kitestance
    @kitestance 2 ปีที่แล้ว +1

    Great teaching. Thank you.

  • @richardradcliffe6178
    @richardradcliffe6178 2 ปีที่แล้ว +1

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

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

    thanks for the tips. good stuff

  • @jatilyadav4000
    @jatilyadav4000 2 ปีที่แล้ว +1

    Amazing video.. Hats off

  • @kran399
    @kran399 3 ปีที่แล้ว +1

    great Content Love from India Sir.

  • @VaibhavSharma-zj4gk
    @VaibhavSharma-zj4gk 2 ปีที่แล้ว +1

    Top quality content. 10/10.

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

    Nice style of teaching ❤

  • @rabiaabbas262
    @rabiaabbas262 3 ปีที่แล้ว +1

    Really good explanation, thanks a lot!

  • @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.

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

    Top Tutorial! Greetz from Germany!!!

  • @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!!!!!!

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

    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

  • @dr.d3600
    @dr.d3600 2 ปีที่แล้ว +1

    Great video ❤

  • @maverick-n6x
    @maverick-n6x ปีที่แล้ว

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

  • @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.

  • @hannahp642
    @hannahp642 2 ปีที่แล้ว +1

    great quality!

  • @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.

  • @spidysense7754
    @spidysense7754 2 หลายเดือนก่อน +2

    You are soooo gooood❤❤❤

  • @LeetCodeSimplified
    @LeetCodeSimplified 3 ปีที่แล้ว +1

    Great video, thx a lot!!

  • @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.

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

    Thanks for your explanatory examples and efforts !!

  • @derpstarz
    @derpstarz 3 ปีที่แล้ว +1

    Good stuff! subscribed

  • @ebcoutinho
    @ebcoutinho 11 หลายเดือนก่อน

    Pure gold found here

  • @zenreefer7817
    @zenreefer7817 2 ปีที่แล้ว +1

    This channel is a fucking GEM

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

    Awesome.... !!! 👍

  • @eyesoap4536
    @eyesoap4536 2 ปีที่แล้ว +1

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

  • @Aaron-sy5yx
    @Aaron-sy5yx 3 ปีที่แล้ว +1

    Dude great video.

  • @miedsekadse7136
    @miedsekadse7136 2 ปีที่แล้ว +1

    Great video

  • @Chris2phaBrown
    @Chris2phaBrown 3 ปีที่แล้ว +1

    happy to have inspired :)

  • @jimfoley2690
    @jimfoley2690 2 ปีที่แล้ว +1

    Great stuff

  • @anonlegion9096
    @anonlegion9096 2 ปีที่แล้ว +1

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

  • @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

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

    Liked and subscribed.

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

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

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

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

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

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

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

    14:13 Gramma song?

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

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

  • @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.

  • @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.

  • @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. 😄

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

    What is this interpreter you are using for code.

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

    thank you

  • @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.

  • @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.

  • @12nov83
    @12nov83 ปีที่แล้ว

    which editor...you used? please

    • @ColorCode-io
      @ColorCode-io  ปีที่แล้ว

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

  • @aburaihan-py4vi
    @aburaihan-py4vi 3 ปีที่แล้ว +1

    Wow!

  • @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.

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

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

  • @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.

  • @Dimy111
    @Dimy111 3 ปีที่แล้ว +1

    Good vid

  • @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 😊✌️

  • @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

  • @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......

  • @kran399
    @kran399 3 ปีที่แล้ว +1

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

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

    i like it

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

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

  • @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 :(

  • @maciekdzikdrums
    @maciekdzikdrums 8 หลายเดือนก่อน

    king

  • @edhead76
    @edhead76 11 หลายเดือนก่อน

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

  • @zahraBatenin
    @zahraBatenin 5 หลายเดือนก่อน

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

  • @spacey6960
    @spacey6960 5 หลายเดือนก่อน

    14:08 "peeeeeerry"

  • @thedelanyo
    @thedelanyo 2 ปีที่แล้ว +1

    I see. Understands. Object.prototype is great great great grandpa of all objects...