Это видео недоступно.
Сожалеем об этом.
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
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 !
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!
@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!
@Yusuf Brecken no problem :D
why are they still here just to make us suffer
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.
When he says : "What Is Happening Here"
Me like : I don't know either :(
i am dum this video say to me
The last bit of this video was extremely useful! THANK YOU
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.
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.
@@davidlira8853 Ooh great
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?
to create objects which has same method but different property value
The new keyword also sets the prototype of the object to its parent which is Circle
e.g Object.setPrototypeOf(newlyCreatedObject, ConstructorFunction)
can you please explain to me what the draw method is? What does it do?
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
You are genious, explaning each piece of code in clear manner!
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.
Nice js talk! I’m learning something new everyday... thanks
And what about ES6's classes? What's the difference between this way of creating objects and classes?
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!
@@juan193 excellent explanation
@@juan193 Thank you, highly appreciate your explanation.
You are awesome. Love your videos
Crystal clear explanation. Thank you, sir!
Amazing explanation thank you❤️❤️
God gifted mind to Mosh
FINALLYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY, BEST EXPLANATION EVER.
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.
Thanks for the wonderfull explanation :)
Bro...you rock! Great tutorials man, thumbs up on all of them. Of course I subscribed :-))
Thank you Mosh, this was really good explaned
Mosh, you the goat.
Thanks
Great lecture
Simple and Superb!
Earned a subscribe for not having a difficult accent and not having terrible sound quality.
Since three days my life stopped working, but after watching your video my life has finally rebooted
what?
what about the getter and setter ? Can that be used in factory functions? Or is that only possible with Constructor Functions ?
Thank you
thank you
wonderful explination!
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);
thanks man !
Thanks Jhonny
Thank you!!
It’s great! Thanks
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)
Can you please explain what does the draw method do?
@@islombekmirsalimov3185 it just displays the text 'draw' on the console when called. Its not going to draw a circle on the console :)
Wow so useful!
The moment you realize - the Factory function itself using Constructor function under hood:
function createCircle() {
return new Object()
;
}
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.
@@Zen-lz1hc You are stating the obvious, try thinking out of the box.
I don't understand the this.draw function in his constructor function. It just prints the word ‘draw’? Am I missing something?
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?
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)..
"Do not get hung up on these developers' strong opinions. They are just a waste of time." 🤣 I love this guy.
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
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.
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.
I'm not sure, this is my own explanation to myself 😂
So, the memory usage on both ways is the same?
dude is godlike
Isn't that creation of object prototype rather then declaring function via constructor? Got bit confused thus my question.
excellent
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?
what happens if I write: const circle = Circle(1); without the new operator??
Running the code and showing output in the console would be helpful
May I ask what is your VScode theme ?
Why using constructor function Circle without putting draw method into Circle.prototype?
pelado del bien te quiero mucho
Danke
Enigmatic!!
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! :)
20% of the video is Camel vs Pascal
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.
not true
I disagree. JavaScript IS Object Oriented. But instead of being class-based, it is prototype-bases. Prototypes are a vital part of JavaScript.
How can i buy your courses using debit card.
I am from India.
Thank you
use cow dung
@@kiraw3188 ur cringe
These courses are also available on udemy. You can buy from there.
@@kiraw3188 Can you please show me how? I could save a lot of money that way :)
@@kiraw3188 Grow up :)
1:48
The only thing I don't understand is setting this.radius = radius. What is the purpose? It's saying object.parameter = parameter
I think its more like objects.property = parameter. "this" refers to the caller of the function, if im not mistaken
"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"
it is just synthetic sugar.
Mosh ... Why you are not in Udemy ...
hi, my name is zinedine is there any way to put it in spanish for latin america
How to create constructor using es6??
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.
I prefer factory functions
❤👍
i dont undestand how can I make a circle with this code
He: constructors are for developers who worked in c# or java ;
Me completely clueless even when coded in c# unity before;
dying in ashes
I feel as though i learned something. but i have no experience in java or C++ and it sounds like AI and Machine learning.
i am dumb, been watching 6 min video for hours but still can't get this :(
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.
m not getting anythingsssssssss.....
Кто русский?
Constructor function looks unnecessarily complicated. Factory function is quite simple.
@@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.
@@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.
@@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.
@@ShoeCar You can also do that with factory functions:
createCircle = (function () {
const draw = function() {
console.log('drawing...');
}
return function(radius){
return {radius, draw};
}
})();
I do not understand how I can use this I am to stupid
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.
Ok well. Which one is faster? I think Factory Functions are faster and Constructor Functions are spending more performance.
But Constructor Functions... only good side is that it can be readable and adaptable to other languages.
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.
@@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?
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.
I fucking hate javascript
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