Это видео недоступно.
Сожалеем об этом.

JavaScript Constructor Functions

Поделиться
HTML-код
  • Опубликовано: 14 май 2018
  • JavaScript Constructor Functions made simple.
    🔥Get the COMPLETE course (83% OFF - LIMITED TIME ONLY): bit.ly/2M1sp4B
    Subscribe for more videos:
    / @programmingwithmosh
    Want to learn more from me? Check out my blog and courses:
    programmingwith...
    / programmingwithmosh
    / moshhamedani

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

  • @Zen-lz1hc
    @Zen-lz1hc 3 года назад +41

    You should know all the ways of creating objects in JS :
    -Object Literals
    -Object.create()
    -Factory function
    -Constructor function
    -Class
    Why ? Because in certain situation one tool is better than the other !

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

      Sorry to be so off topic but does any of you know of a tool to get back into an Instagram account..?
      I somehow lost my account password. I love any assistance you can offer me!

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

      @Misael Justin It worked and I actually got access to my account again. I'm so happy!
      Thank you so much, you saved my account!

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

      @Yusuf Brecken no problem :D

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

      why are they still here just to make us suffer

    • @CapeSkill
      @CapeSkill 2 года назад +5

      I disagree, I don't think it's a necessity to know all ways. Just like Mosh said at the end of the video, you can pick one pattern and stick with it.

  • @exosmexos915
    @exosmexos915 4 года назад +64

    When he says : "What Is Happening Here"
    Me like : I don't know either :(

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

      i am dum this video say to me

  • @mariomerino9758
    @mariomerino9758 4 года назад +30

    The last bit of this video was extremely useful! THANK YOU

  • @codypayne3711
    @codypayne3711 4 года назад +8

    THANK YOU!!! I did NOT understand what the effective difference was between factory and constructor functions -- thanks for explaining that they're just different tools to get the same thing done.

    • @davidlira8853
      @davidlira8853 4 года назад +8

      The constructor function(which is also an object) has a property called prototype. For example:
      function Car(model, year, color) {
      this.model = 'Honda';
      this.year = 2020;
      this.year = Blue;
      }
      Car.prototype.drive = function() {
      console.log('Drive ' + this.model);
      }
      You can add methods to the prototype property of the constructor function. So every object that you create will have access to those methods.
      This idea is called inheritance. JavaScript achieves inheritance via prototypes.
      Let me know if you need more explanation.

    • @kennyj.i9463
      @kennyj.i9463 2 года назад

      @@davidlira8853 Ooh great

  • @sunitmody6064
    @sunitmody6064 4 года назад +28

    Hi Mosh, as a new programmer I would like to suggest you include some context for the use of constructor function. I.E. What are they used for?

    • @pulok9909
      @pulok9909 4 года назад +10

      to create objects which has same method but different property value

  • @jsprodev2425
    @jsprodev2425 6 лет назад +17

    The new keyword also sets the prototype of the object to its parent which is Circle
    e.g Object.setPrototypeOf(newlyCreatedObject, ConstructorFunction)

  • @keifer7813
    @keifer7813 2 года назад +5

    I think it's important to be familiar with both ways since you'll be reading others' code and be lost if they use constructor functions but you only know factory functions

  • @nagakrushnayelisetty6880
    @nagakrushnayelisetty6880 5 лет назад +4

    You are genious, explaning each piece of code in clear manner!

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

    Instead of x you could explicitly use let this = {}, that is essentially what happens in the first line of the constructor function. Helped me to learn it that way.

  • @sonoftroy8572
    @sonoftroy8572 6 лет назад +7

    Nice js talk! I’m learning something new everyday... thanks

  • @matavic25
    @matavic25 6 лет назад +12

    And what about ES6's classes? What's the difference between this way of creating objects and classes?

    • @juan193
      @juan193 6 лет назад +10

      Since JS is super elastic and flexible, adding many routes to get to the same goal (kinda like PHP and other web technologies where you can just do what you please and if you're not careful you'll end up in a performance/code hell) the difference comes to maintainability, readability and, if you do care, performance (not just machine performance) and portability to other stricter languages.
      In this case a Constructor function is just a few steps away from being a proper class (Since classes usually need a constructor so you can append the 'new' keyword). Writing a class adds certain syntactic sugar and also helps your IDE or code editor make suggestions to whenever you want to access methods, props, getters, setters, etc. of certain object (that usually comes from a class).
      Usually, with a computer science background, you learn programming paradigms along with more robust/mature/older/stricter (whichever might apply, not saying JS is any of the former) languages like Java or C (make that C#, C++ or just plain ANSI C) and practice concepts like functions, objects, classes, etc. These paradigms lead you to adopt certain practices to write robust code and, in short, be able to shape real world problems to properly express them in lines of code. Here's where the paradigm's concepts come into play, being able to, say, a thing(Object) like "Person" then go through inheritance to create i.e "Teacher" and so on and so forth.
      I mean, these are just my 2 cents on the matter, from what I've gathered from certain JS tutorials, my own experience as a developer and from what Mosh says on the video. Hopefully you have a clear idea now!

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

      @@juan193 excellent explanation

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

      @@juan193 Thank you, highly appreciate your explanation.

  • @ritsk4338
    @ritsk4338 4 года назад +2

    You are awesome. Love your videos

  • @cyanozoid2706
    @cyanozoid2706 4 года назад +9

    Crystal clear explanation. Thank you, sir!

  • @majdalkwaja9792
    @majdalkwaja9792 5 лет назад +3

    Amazing explanation thank you❤️❤️

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

    God gifted mind to Mosh

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

    FINALLYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY, BEST EXPLANATION EVER.

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

    great video, still a bit confused by this topic. So I think its more just practicing and playing around with constructive functions to understand this.

  • @sureshmg6786
    @sureshmg6786 4 года назад +2

    Thanks for the wonderfull explanation :)

  • @SuperLukiano
    @SuperLukiano 5 лет назад +3

    Bro...you rock! Great tutorials man, thumbs up on all of them. Of course I subscribed :-))

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

    Thank you Mosh, this was really good explaned

  • @21rooms1willdo
    @21rooms1willdo 3 года назад

    Mosh, you the goat.

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

    Thanks

  • @AkashKumar-lr6hc
    @AkashKumar-lr6hc 2 года назад

    Great lecture

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

    Simple and Superb!

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

    Earned a subscribe for not having a difficult accent and not having terrible sound quality.

  • @samsam-zu7zc
    @samsam-zu7zc 5 лет назад

    Since three days my life stopped working, but after watching your video my life has finally rebooted

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

    what about the getter and setter ? Can that be used in factory functions? Or is that only possible with Constructor Functions ?

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

    Thank you

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

    thank you

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

    wonderful explination!

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

    Hi mosh do we really have to instantiate a factory function? I always run this function directly specialy weh setting an element: Example: createCircle(1);

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

    thanks man !

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

    Thanks Jhonny

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

    Thank you!!

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

    It’s great! Thanks

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

    Why not include the new ES6 notation with class and constructor?
    The code would read something like:
    class Circle {
    constructor(radius){
    this.radius = radius;
    }
    draw() {
    console.log('draw')
    }
    }
    const myCircle = new Circle(radius)

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

      Can you please explain what does the draw method do?

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

      @@islombekmirsalimov3185 it just displays the text 'draw' on the console when called. Its not going to draw a circle on the console :)

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

    Wow so useful!

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

    The moment you realize - the Factory function itself using Constructor function under hood:
    function createCircle() {
    return new Object()
    ;
    }

    • @Zen-lz1hc
      @Zen-lz1hc 3 года назад

      Veron Nahkur
      No it doesn't !
      The factory function uses Closures under the hood .
      The consturctor function uses "this" operator and the "new" operator under the hood.

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

      @@Zen-lz1hc You are stating the obvious, try thinking out of the box.

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

    I don't understand the this.draw function in his constructor function. It just prints the word ‘draw’? Am I missing something?

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

    do any of you guys understand how const x is related to anything else in this? if it were const x = new Circle(1) I could understand how its related. but x is being initialized as an empty object. so hows it related to Circle? or are constructor functions global where any other objects or functions created in the same file/document are automatically associated with the constructor function?

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

      The const x was just something he showed to get an idea what execution engine does under the hood...
      Basically the new keyword instantiates an object (sets aside seperate memory space) and initializes the space/object with the info given in blueprint (which is the constructor function here...analogy of a class in Java).
      So now the const circle points to this memory space/object which is initialized as per the blueprint.
      So now you are referring a created object with 'circle' variable and can use it like any other Object in JS (like you would anObject literal)..

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

    "Do not get hung up on these developers' strong opinions. They are just a waste of time." 🤣 I love this guy.

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

    Can someone explain me why the constructor function returns: Circle { radius: 1, draw: {...} }
    but the factory function returns just: { radius: 1, draw: f draw {...} }
    tested with playcode.io by console-loging the myCircle & circle variables

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

      It's just how console works - it prints out the name of constructor function.
      In case of factory function, it should print Object { ... }, but console is hiding the keyword 'Object' by default.

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

      In factory function, draw is declared as a complete function inside.. whereas in constructor function, it is treated as object and inside that, a function is declared.

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

      I'm not sure, this is my own explanation to myself 😂

  • @aaabbb-qv4ff
    @aaabbb-qv4ff 4 года назад

    So, the memory usage on both ways is the same?

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

    dude is godlike

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

    Isn't that creation of object prototype rather then declaring function via constructor? Got bit confused thus my question.

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

    excellent

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

    i found out that if i write the same constructor function for Circle with ES6 it doesn't work. i tried writing it like this:
    "
    var Circle=(radius)=>{
    this.radius=radius
    this.draw = function (){
    console.log("drawing for radius:",radius)
    }
    }
    "
    an then i got an error saying "Uncaught TypeError: Circle is not a constructor"
    any clues?

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

    what happens if I write: const circle = Circle(1); without the new operator??

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

    Running the code and showing output in the console would be helpful

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

    May I ask what is your VScode theme ?

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

    Why using constructor function Circle without putting draw method into Circle.prototype?

  • @Avocado.777
    @Avocado.777 2 года назад

    pelado del bien te quiero mucho

  • @samsam-zu7zc
    @samsam-zu7zc 4 года назад

    Danke

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

    Enigmatic!!

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

    I laughed out loud on that part about not hanging on which pattern is better. It's a waste of time! :)) so true. You are e doing an excelent job with these tutorials! Mosh rocks! :)

  • @jessneurismfarmer
    @jessneurismfarmer 4 года назад +3

    20% of the video is Camel vs Pascal

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

    Mosh explanation is always very neat and good.
    My 2 cents about this topic:
    Factory functions are a more reliable way to make objects.
    Objects created via constructor have binding problem, those objects simply lose their scope in some occasion.
    JavaScript is a functional programming language natively, not an object oriented one.
    Messing with prototypes can have a bad impact in terms of performance.

    • @darealmattai
      @darealmattai 6 лет назад +3

      not true

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

      I disagree. JavaScript IS Object Oriented. But instead of being class-based, it is prototype-bases. Prototypes are a vital part of JavaScript.

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

    How can i buy your courses using debit card.
    I am from India.
    Thank you

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

      use cow dung

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

      @@kiraw3188 ur cringe

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

      These courses are also available on udemy. You can buy from there.

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

      @@kiraw3188 Can you please show me how? I could save a lot of money that way :)

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

      @@kiraw3188 Grow up :)

  • @gracep2910
    @gracep2910 7 дней назад

    1:48

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

    The only thing I don't understand is setting this.radius = radius. What is the purpose? It's saying object.parameter = parameter

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

      I think its more like objects.property = parameter. "this" refers to the caller of the function, if im not mistaken

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

      "this" refers to the object itself. So, you know it belongs to this specific object. Many times you'll have code with different "objects" and you must know what "this" refers to. I suggest you watch Mosh's next vid, "Javascript This Keyword"

    • @aaabbb-qv4ff
      @aaabbb-qv4ff 4 года назад

      it is just synthetic sugar.

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

    Mosh ... Why you are not in Udemy ...

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

    hi, my name is zinedine is there any way to put it in spanish for latin america

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

    How to create constructor using es6??

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

      You can't create a constructor per say. You use the already available constructor to create a new object. In ES6 you use constructor inside a class.

  • @solmazk7418
    @solmazk7418 5 лет назад +12

    I prefer factory functions

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

    ❤👍

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

    i dont undestand how can I make a circle with this code

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

    He: constructors are for developers who worked in c# or java ;
    Me completely clueless even when coded in c# unity before;
    dying in ashes

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

    I feel as though i learned something. but i have no experience in java or C++ and it sounds like AI and Machine learning.

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

    i am dumb, been watching 6 min video for hours but still can't get this :(

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

      It's because just seeing this with no context in how you can apply it to a problem in the real world won't make much sense. It's basically higher-order implementation for solutions you would need in applications or some kind of functionality.
      My advice would be to actually think of a few things where you can apply a constructor function (like Animal for example, then make new animals using that constructor design pattern in mind.
      Think of the problem, write it down if you need to and study it -> Study how a given design pattern will solve the problem -> Implement design pattern
      Animal class pulling from an API and utilized into a VueJS environment is a good starting point to begin in practicing with Constructor patterns, you are creating new animals from an API using the pattern and processing that in a Vue Template... This is one of the many examples you can practice with to learn.

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

    m not getting anythingsssssssss.....

  • @alfo-qd1me
    @alfo-qd1me 5 лет назад +1

    Кто русский?

  • @Ali-lm7uw
    @Ali-lm7uw 5 лет назад

    Constructor function looks unnecessarily complicated. Factory function is quite simple.

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

      @@programmingwithmosh The big advantage to using the Constructor function is saving processing power. If you create 10 Circle objects from the Factory function you are also creating the draw function 10 times. If you create 10 Circle objects from the Constructor function you only create 1 draw function. This doesn't matter much in this comparison but if you create an entire web app using Factory functions you will have a slower website.

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

      @@ShoeCar It can matter with larger datasets though. Its one thing to have 10 circle objects with 10 duplicate functions. Its another to have 50,000 of them.

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

      @@ShoeCar You are close. However, the way the constructor function is written in the video will actually create 10 circle objects with each one having its own draw function for a total of 10 draw functions. If we want only 1 draw function, we would have to modify the code to look like what is shown below:
      _________________________________________________
      function Circle(radius) {
      this.radius = radius;
      }
      Circle.prototype.draw = function() {
      console.log('draw');
      }
      const Circle = new Circle(1);
      _________________________________________________
      This concept is called inheritance using prototypes.

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

      @@ShoeCar You can also do that with factory functions:
      createCircle = (function () {
      const draw = function() {
      console.log('drawing...');
      }
      return function(radius){
      return {radius, draw};
      }
      })();

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

    I do not understand how I can use this I am to stupid

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

      He is not actually drawing on any canvas like tool...Its to give an example of object creation like:
      example 1:
      Object is a ball. It has virtues (properties): radius,material,mass
      and
      behaviour(methods): rolls, bounces, swings etc.
      Now virtues can differ like one ball can be tennis ball...other can be volleyball... So both are a type of 'ball' object. But their properties will differ...
      But the blueprint (properties and methods) will be similar. So both can be created with same constructor function/factory function.
      Hope this helps little bit.. And yeah you are not stupid...Just stuck...I learned some Java and then jumped into JS...So that helped me grasp JS better.

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

    Ok well. Which one is faster? I think Factory Functions are faster and Constructor Functions are spending more performance.

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

      But Constructor Functions... only good side is that it can be readable and adaptable to other languages.

    • @scriptin3168
      @scriptin3168 6 лет назад +4

      I ran a speed check on both of these using console.time() and console.timeEnd(). The constructor is significantly faster. It completes in around 0.5 ms where as the factory comes in at 3.9 ms. The factory functions are considerably more easy to remember, but the constructor way 154% faser.

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

      ​@@scriptin3168 Hi guys :) I've been learning JS intensively for over a month now and I was also under the idea that the reason why the Constructor exists is for having a sort of model to build all objects around it in a more optimised way. So in theory it should be faster than the Factory right?

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

      The big advantage to using the Constructor function is saving processing power. If you create 10 Circle objects from the Factory function you are also creating the draw function 10 times. If you create 10 Circle objects from the Constructor function you only create 1 draw function. This doesn't matter much in this comparison but if you create an entire web app using Factory functions you will have a slower website.

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

    I fucking hate javascript

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

    this code does not even work you didnt even log it all you do is talk about factoRy FuNCtioNs And ConsTrUCtoR FUCNTIONS im HERE FOR CONSTRUCTOR FUNCTIONS IDC ABOUT FACTORY AND YOU DIDNT EVNE LLOOUT TWNHKLNAKLFWAN