I can probably count on one hand how many truly clear and straight forward youtube coding tutorials I've watched, this is one of em, hitting subscribe!
Great video! Being an old-school C++ developer, I personally never understood why JavaScript ever needed to borrow the class syntax. One cannot really deny anymore that classes exists in JavaScript, they surely didn't. I prefer the syntax 'prototype' above 'class'. Many early C++ book editors around 1990 had a hard time explaining what a class is all about, almost apologetic for the confusing word choice. A prototype really says what it does, as it shapes how the instantiated object will look like, while a class has nothing to do with classification.
I never dreamed I can understand these class things, but after this tutorial, those abstract things go straight into my head without any resistance. legend teacher, as always thank you.
Steve, you are the ONLY ONE I found online, that explained well enough so I could understand, I always tried to find a relationship (a kind of "translation") between functions and classes and you simply explained it. Perfect video. Thank you very much.
"It is important to understand that the class syntax is being interpreted as using the prototype syntax and that CLASSES do NOT exist in JavaScript." Great 👍
Omg! I finally understood prototypes - I have watched three different tutorials and I still did not get that...until I came across this video! Thank you so much!
such a good tutorial, you don't skip anything and actually understanding what's a class doing and how to simulate it using prototype explains the logic behind it.
What a clear and insightful video on what can be a very complicated concept! I've saved your 'JavaScript from the start' playlist and will be working my way through, one per day. Thanks Steve for the great education!
At 11:13, if you set the prototype of EmployeeP to PersonP.prototype, the EmployeeP.__proto__ becomes the PersonP.prototype, and the EmployeeP.prototype stays the same it was, that's what happens for me at least. Because of that the methods inside PersonP.prototype cannot be called through the objects created by EmployeeP. I don't know if I did something wrong, but to fix that I simply wrote Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype), so now the prototype object of EmployeeP function is a child of the prototype object of PersonP function, I think that's how the prototype chain for classes is too.
A lot of libraries use the manual prototype method and there are some neat tricks you can do with it. I first saw this when analysing mongoose code. There are some challenges if you want to represent this with types in a typescript project, I found using class syntax to be less pain in that regard.
I definitely have things that I do with prototype and then there are some cases - Web Components, extending Events, extending Errors where I will use the class syntax.
After making a connection between the EmployeeP object and the prototype of the PersonP using Object.setPrototypeOf() method, a new prototype method(function) is added on the the EmployeeP object (in the line number 51) with the name of employeeInfo. So, my question is that whether this new method (employeeInfo) will be added to the prototype of PersonP or another prototype object of the EmployeeP? BTW your way of imparting the information (idea) is unmatchable, it's GOLD STANDARD. I will try to teach my students your way.
The new method on line 51 is only being added to the prototype of EmployeeP. With setPrototypeOf on line 50 we are explaining what the next step in the prototype chain will be. If some method is not found inside EmployeeP.prototype then JS will look inside PersonP.prototype. This video also helps my students - ua-cam.com/video/01jVgCK-HX4/v-deo.html
Just discovered your channel, man .. if only you've been around 20 years earlier, I would be a JS master by now :) The thing that confused me for many years is what "this" means depending on the different contexts. I was a AS3 developer for many years, so i was used to the class logic, never understood the "prototype" concept because of that. When "class" was introduced in ES i finally could work the way i was used to. But thats why i've never understood "this". Now, i even think the prototype way of doing things is more logical. And understanding it clears up a ton of other things in JS that puzzled me.
Glad I could help. I loved teaching AS3 in Flash. Having the visual part made it so much easier to explain the Class concept. I did a video recently on "this" - ua-cam.com/video/eWDXgsIgTGk/v-deo.html
Nice content, nice explanation, I'm a newbie & I could derive a lot of sense out of this. Helpful & v.much to the point. Clean clear crisp. And your voice is so cool :p Cheers keep this great work going.
Thanks it made it clear to me that even if it ends up being the same thing, classes makes it more clear that they are tied together. I do wonder if one way performs better than the other tho but its probably not that important.
@@SteveGriffith-Prof3ssorSt3v3 Hi, Steve. Loved the video, thank you. I came here with a burning question that perhaps flew over my head. If they're doing the same thing, then what's the point of the redundant syntax and why chose one syntax over of the other?
I get back undefined if i replace this with EmployeeP. I don't understand why. @10:06 let EmployeeP = function(nm, id, salary){ PersonP.call(EmployeeP, nm, id); this.salary }
@@SteveGriffith-Prof3ssorSt3v3 With the code fix I now get NaN. I'm just confused why I can't substitute "this" for EmployeeP on line 47. Sorry for being noob.
@@nigelbrie5693 Never apologize for learning. Here is another video where I explain about prototype and `this`. ua-cam.com/video/eWDXgsIgTGk/v-deo.html It should help you.
As an advanced novice JS coder, I always found 'prototypes' confusing ... Your video makes the case for the class paradigm vice prototype model in my view ... Coming from the Java and Python world, classes and subclasses are the way to go and are more OOP than 'prototypes' ...
They both do the same thing internally. Both syntaxes are working with prototypes. The Class syntax was partly added to make the transition easier for people coming from languages like Java. Partly it was yet another attempt at trying to simplify something that has been a confusing mess for 20 years.
Hi Steve, I am just starting my career in coding and have to say you are like a god of coding for me. I read blogs, excerpts from books, and what not but the way you explain things is just amazing. I am preparing for the MCSA-70-480 exam as a part of my apprenticeship and these tutorials are so helpful for a beginner like me. Just wanted to know if by any chance do you take personal coding classes or any sort of official coding lessons if somebody is interested in learning from you 1-1? My learning at this point in time is exam based and there are so many things that I come across in practice questions that I just can't understand and hence feel the need for proper mentoring for expedited learning.
I teach students, but only in my program at Algonquin College - www.algonquincollege.com/mediaanddesign/program/mobile-application-design-and-development/ I don't do mentoring or one-on-one tutoring. Just no time for it.
Without the keyword new, any function returns whatever is written after the first return keyword in that function. If the function has no return statement then it returns undefined.
In JS, classes and closures are two different things. closures in JS are a built-in feature that allows you to maintain reference to a value that would otherwise have been lost, so that you can use it at a later time. Closures will be used both with objects and prototypes as well as with simple functions and loops. JS classes are a syntactic sugar that lets you define/create Objects and their prototypes with a simplified syntax. As far as performance between classes and older Object.create syntax, there is no real difference. They both create a JS object and a prototype.
@@fifilulu ok. Well the answer is the same. Classes are just syntactic sugar. They create the exact same prototypes behind the scenes . No difference in performance because they are the same thing
@@SteveGriffith-Prof3ssorSt3v3 Interesting, I noticed that most experienced JS developers prefer prototypes. I concluded it was faster, but it is probably because classes have been lately added to the language.
@@fifilulu you will see a lot more of the class syntax when working with React developers. More experienced developers will be more likely to use the older syntax, like you said the class syntax is newer
I was struggling with 2 things, what a class really is (in JS) & what practical purpose it serves for the work I do. You have answered that perfectly .. knowing that the class syntax is just syntactic sugar for functions makes my brain happy! Subscribed.
It's just two different syntaxes for the same thing. Real #private variables are available in classes but you can mimic them with proper scoping and prototypes.
Thank you so much for the very concise information. Sometimes I see projects on Github mixing these techniques (Especially Node.js projects). Why is that? Is there some advantage to mixing these or using one or the other?
Classes are just syntactic sugar for prototypes. In the latest updates to classes there are a couple unique things. But for the most part it is a developer preference on how to write the code. Sometimes it will depend on what else they are doing in the code and if it is more functional or more object oriented.
@steve griffith : Hello Steve. This is really Awesome. By far the best Explanation ever. All your Videos are Awesome. Keep Rocking. A Small Clarification, I feel it has to be Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype). [ You have written EmployeeP. This causes an error and I'm not able to call getDetails Function from the Base Class. ] Please do correct me if I'm wrong. Thanks
Yeah. I fixed that in my code sample afterwards. I also have a new video that I did to visually explain prototypes - ua-cam.com/video/01jVgCK-HX4/v-deo.html
Why do you need line 50? Where you set prototype? It seems that you can have inheritance just with the PersonP.call line. I imagine I'm missing some inheritance functionality that would be missing but I can't think of it.
You can. As long as you changed line 50 to: Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype); as mentioned in the description. There was a typo in the video.
Line no : 50, The setProtoType should be set on EmployeeP's prototype right? Object.setPrototypeOf(EmployeeFun.prototype,PersonFun.prototype) // extends
There are 3 parts to this. 1. The object. 2. The constructor function that made the object. 3. The prototype object. The function (2) can access the prototype object with the `.prototype` keyword. The object (1) can access the prototype object with the dunder-proto keyword. Here is another video I did on the topic - ua-cam.com/video/01jVgCK-HX4/v-deo.html
By using setprototype method, getDetails method of Person's prototype didn't inherited by EmployeeC. So where is the inheritance now? I wrote the same code in my pc but didn't inherited the method by EmployeeC. Plz explain
Did you get type the code that was on the screen or take the updated version from GitHub? If you typed the version on the screen did you read the note in the description about line 50? With that change, you can add this to the end: console.log(mary.getDetails()); and it works fine.
From what I'm reading, the use of Object.setPrototypeOf() is highly discouraged due to massive performance issues. I also miss how this relates to __proto__ in this very example. Last thing I noticed is that doing SuperClass.call(this, params) is called constructor theft in Nicholas Zakas' excellent book "Principles of object-oriented Javascript", and I wonder if there's any alternatives to that.
Excellent tutorial as usual. I was wondering though, why not add getDetails to PersonP like you did with the properties? I.e. this.getDetails = function() { // code block }. This makes the prototype way look more like the class way. I assume they are just different ways of doing the same thing, is that right?
Or there seems to be a difference: the way I mentioned makes 'getDetails' and enumerable property (or method), and using PersonP.prototype.getDetails puts the getDetails method on the PersonP prototype (and anything on the prototype is NOT enumerable). Is that correct?
@@theunknowndev2913 they are different. Classes use actual inheritance and copying methods and properties to the child objects. Prototypes use delegation
@@SteveGriffith-Prof3ssorSt3v3 Oh, I see. So would I be correct in saying that classes in ES6 are *not* technically syntactic sugar, in that using classes in ES6 copies methods and properties to the child objects using class-based inheritance, whereas instantiating functions uses delegation (aka prototype-based inheritance)? Assuming that syntactic sugar means an easier syntactic way to do the exact same thing.
@@theunknowndev2913 they ARE syntactic sugar. They don't copy the properties to the child objects. Delegation means that the properties stay with the single parent object and the reference to the child is used as 'this' when calling on those properties.
@@SteveGriffith-Prof3ssorSt3v3 I see. I think I understand. This jibes with the fact that classes are syntactic sugar over prototypical inheritance. I mistook the sugar for the delegation, but the sugar is on top of the delegation. Thanks for your help and great content! I will keep learning :).
You can create a prototype chain that is any length that you need. However, each object's constructor function can only have one prototype. The prototype will be one step in the prototype chain. If you are asking about combining the properties and methods of a bunch of different objects into a single new object, then you are talking about composition instead of inheritance. ua-cam.com/video/fbpXQ0e8Mp8/v-deo.html
Real stuff starts at 9:25, object.call() is what super is doing; extends is the syntax sugar used to set prototype of child function to be the same as parent function; In this way, all functions in parent become automatically available to child function through prototype mechanism
Hi Steve, thanks for this video. I came back to this again after refactoring some code into factory functions and away from classes. My question is: with what you've shown here, will we still encounter the various pitfalls with 'this'? (ie. having to bind explicitly when invoked from another function -- my intuition says yes because this illustrates an alternate syntax for the same end result). To that end, would you recommend a more functional / composition based approach where factory functions return objects with certain properties and then object types are returned by composing those functions? Cheers!
With JS I would definitely recommend using a functional / composition approach to building things. Classes in JS are not what you expect from "class" in other languages. It is a nice clean syntax if you are building objects that will have a limited scope and interactions with other object types. However, when architecting anything in JS you need to think in terms of prototypes and composition works better there.
hi just wanted to know doesn't it breaks linkage with Function.prototype with EmployeeP ? I guess instead "Object.setPrototypeOf(EmployeeP, PersonP.prototype)" we should use "Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype)"
At line 47 PersonP.call(this, nm, id) is there any other way to write it using the setPrototypeOf or Object create method? Thank you very much for your tutorial. Amazing as always!
We need to call the PersonP constructor to give us the name and id properties and their values. setPrototypeOf is just creating the prototype chain for inheritance. It is like calling super( ) inside the Class syntax's constructor( ) method.
In some ways it does. But if you understand how the prototype system works then you just need to learn how the class keyword works with this. Just don't try to force your understanding of `class` from other languages into JS.
As we discussed in the GitHub comments, this response is more for other people interested in the answer. Most of what makes up ES6+ are additions to the language, not replacements. We have options on how we write our code - a functional style or an event-driven style or an object oriented style... or a blend of those. ES6+ gives us options. ES6+ is not invalidating any code that currently exists. The browsers still support all the JS going back to the late 90s. (few very minor browser specific exceptions). When it comes to creating Objects and their prototypes you get to choose which style/approach that you want to use. If you are starting out, pick one. Learn it well. But you also need to learn what is going on behind the scenes with that syntax. Eventually, you will need to learn the other syntaxes and how they relate to one another. Almost all developers have to work with other developers. We're a stubborn and opinionated bunch. Teams need to agree on a style for how code is written and Objects are created. Even if you are transpiling your JS for backward-compatibility in the browser, your team mates need to be able to read and work with your code. Sometimes you will be lucky and get a team that all like the same style and approach. Other times you will need to adapt. JS is a journey. You will never stop learning. The language continues to grow and adapt. That can be scary but it is also exciting.
@@SteveGriffith-Prof3ssorSt3v3 Point taken. But i must say, i think it's a perfectly fine idea, as a way to get new coders started off on the right foot, for a new learner to start with ES6+, and then add "oh by the way, here's the old style in case you come accost it." Cuz i think it's easy for new coders to get overwhelmed, and not get a clear emphasis on what's the new standard vs outdated ways.
@@johnywhy4679 This is a great point. As a newcomer to JS, the burning question in my mind the whole time was..."which one should I use for best practice" I read other comments that it's just syntactical sugar, but I also read stuff that suggests object.assign vs spread syntax is much slower. I'm probably not comparing apples to apples here, so forgive me but it's the type of stuff that twists me up sometimes.
To me, it feels like Typescript interfaces and type aliases can do all the things that you would use classes/prototypes to do. I feel like i might be wrong about this. Does anybody know anything about this?
Typescript is a superset of ECMAScript... which is JavaScript. It just has extra support for things like primitive datatypes that are strongly typed, intefaces, enums, an extra scope level, etc. End of the day it still has JS under the hood with prototypes.
It should be: Object.setPrototypeOf(EmployeeP.prototype, PersonP.protoype) With code shown in video, you're effectively attaching the employeeInfo() method to PersonP prototype, meaning even PersonP instances would have that method after that point.
It's all prototypes really. So, there is no performance difference. Just a personal choice as long as you understand how the prototypes are created and used.
You can write React JS apps with or without the JavaScript class syntax. A lot of what you do in React will typically be with the class syntax. Just keep in mind that behind everything it is always prototypes, not real classes.
Is there a way I can increment using a variable with this? For example: this.variableName++; I'm trying to do it and the system gives me an error of "cannot read property of undefined". I've been googling and applying some other things like this.variableName = this.variableName + 1; but doesn't work. Thank you for all the help, Steve. Your explanations are the best.
Yes you can have variables that are associated with an instance of the class/object. The way you write the code to increment really depends on how you write the object factory / constructor / class constructor. In the class example I had at the start of this video, if I had a method like this: add() { this.id++ } If would be incrementing the value of id inside the object created by calling new PersonC("Bob", 123); So, this code: let bob = new PersonC("Bob", 123); bob.add( ); would increment bob's id to 124.
Here is a code sample of a class that has a static method which will increment through possible values for instance id values. The id param for the constructor is optional. If you pass it then it will validate that the number is not used. If it is then it finds the next available id. gist.github.com/prof3ssorSt3v3/ff1716453c0858b77cf1f0a652c90ea8
Hi, Steve good explanation, but I wonder, can PersonC get salary method from Employee as the will have a link between them or it is allowed only for Employee as its prototype is PersonC Your suggestions??? Thanks in advance!!!
I assume that you are asking about EmployeeC. salary is a property inside of EmployeeC. EmployeeC extends PersonC, which means that the CmployeeC type objects have access to things from inside of PersonC, not the other way around.
@@SteveGriffith-Prof3ssorSt3v3 Ok Employee type have an access to the elements inside PersonC ,but what about opposite version, can PersonC have an access to things inside Employee
I can probably count on one hand how many truly clear and straight forward youtube coding tutorials I've watched, this is one of em, hitting subscribe!
Yeah each time I stumble on a video he made I feel like someone with confident knowledge is showing something useful. I subscribed too
My head is still spinning, but this breakdown helped me understand how to use classes more. Thank you so much.
I've been a Javascript programmer for more than 10 years, but suddenly, you opened my mind to a whole new sight to OOP in Javascript !!
Great video! Being an old-school C++ developer, I personally never understood why JavaScript ever needed to borrow the class syntax. One cannot really deny anymore that classes exists in JavaScript, they surely didn't. I prefer the syntax 'prototype' above 'class'. Many early C++ book editors around 1990 had a hard time explaining what a class is all about, almost apologetic for the confusing word choice. A prototype really says what it does, as it shapes how the instantiated object will look like, while a class has nothing to do with classification.
I never dreamed I can understand these class things, but after this tutorial, those abstract things go straight into my head without any resistance. legend teacher, as always thank you.
Steve, you are the ONLY ONE I found online, that explained well enough so I could understand, I always tried to find a relationship (a kind of "translation") between functions and classes and you simply explained it. Perfect video. Thank you very much.
Same thing here bro :)
"It is important to understand that the class syntax is being interpreted as using the prototype syntax and that CLASSES do NOT exist in JavaScript."
Great 👍
This is exacly what I'm looking for! Now it makes more sense why the syntax in class is constructed in a bit of a weird way. Many thanks!
I think in 11:16, the line should be Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype) instead.
Great video! I love it!
Yes that line was changed in the description and in the code gist.
Omg! I finally understood prototypes - I have watched three different tutorials and I still did not get that...until I came across this video! Thank you so much!
No bs, straight to the point, clear explanations with clear examples. So underrated!
After 10 videos on constructors, classes, and prototypes in javascript, finally a video that makes me really understand....thank you.
such a good tutorial, you don't skip anything and actually understanding what's a class doing and how to simulate it using prototype explains the logic behind it.
one of the best if not the best javascript channels in youtube
great way to explain, clear and in a not too fast speed, so the brain can follow. thank you for the great tutorial.
Yooooo...been searching for a clear instructional video on this topic, finally found it. Thanks a lot.
So happy I found your channel, I could cry! You’re making every subject I was shaky on just make sense!
What a clear and insightful video on what can be a very complicated concept! I've saved your 'JavaScript from the start' playlist and will be working my way through, one per day. Thanks Steve for the great education!
This is so useful I cannot explain how much it made my learning prototype easy
At 11:13, if you set the prototype of EmployeeP to PersonP.prototype, the EmployeeP.__proto__ becomes the PersonP.prototype, and the EmployeeP.prototype stays the same it was, that's what happens for me at least. Because of that the methods inside PersonP.prototype cannot be called through the objects created by EmployeeP. I don't know if I did something wrong, but to fix that I simply wrote Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype), so now the prototype object of EmployeeP function is a child of the prototype object of PersonP function, I think that's how the prototype chain for classes is too.
I have never seen a explanation like this really u r a great teacher sir applauds 🙏
A lot of libraries use the manual prototype method and there are some neat tricks you can do with it. I first saw this when analysing mongoose code.
There are some challenges if you want to represent this with types in a typescript project, I found using class syntax to be less pain in that regard.
I definitely have things that I do with prototype and then there are some cases - Web Components, extending Events, extending Errors where I will use the class syntax.
Thank you so much. I am not good at english but your explanation is amazing. I can understand whole things. Thank you.
I can't stress how clear this was. Thanks
you are the best! you have nice voice and speech and so good at explaining, thank you
You truly deserve a Subscribe. Thank you for breaking down the complexities of a very confusing language!
Very concise explanation. Better than code bootcamp. Subscribed
Thank you so much, you have helped me sort out the details that were getting mixed up in my head.
The beeeeeeeeeeest explanation ever.
Thank you so much mate.
Fantastic explanation. I can always count on this channel to clear things up. Thanks man.
You are a true engineer, thanks man
Prime level content!! You are really good at JS❤🎉
Thank you! Steve, It's a great tutorial, and your explanation is really great. :-)
Great tutorial with super clear explanations! Thanks a lot!!
this channel is pure gold.
And so underrated.
After making a connection between the EmployeeP object and the prototype of the PersonP using Object.setPrototypeOf() method, a new prototype method(function) is added on the the EmployeeP object (in the line number 51) with the name of employeeInfo. So, my question is that whether this new method (employeeInfo) will be added to the prototype of PersonP or another prototype object of the EmployeeP?
BTW your way of imparting the information (idea) is unmatchable, it's GOLD STANDARD. I will try to teach my students your way.
The new method on line 51 is only being added to the prototype of EmployeeP. With setPrototypeOf on line 50 we are explaining what the next step in the prototype chain will be. If some method is not found inside EmployeeP.prototype then JS will look inside PersonP.prototype.
This video also helps my students - ua-cam.com/video/01jVgCK-HX4/v-deo.html
Thank you for creating this. Very good!
Great explanation on JS classes. Thanks Steve.
I have a new video about classes too - ua-cam.com/video/tqBP5ZX8F0c/v-deo.html
Can someone explain please? 10:26
How can he pass 3 arguments (this, nm, id) to a function PersonP, that has only 2 properties (nm, id) ?
ua-cam.com/video/uBdH0iB1VDM/v-deo.html
@@SteveGriffith-Prof3ssorSt3v3 Thank you so much!
Just discovered your channel, man .. if only you've been around 20 years earlier, I would be a JS master by now :) The thing that confused me for many years is what "this" means depending on the different contexts. I was a AS3 developer for many years, so i was used to the class logic, never understood the "prototype" concept because of that. When "class" was introduced in ES i finally could work the way i was used to. But thats why i've never understood "this". Now, i even think the prototype way of doing things is more logical. And understanding it clears up a ton of other things in JS that puzzled me.
Glad I could help. I loved teaching AS3 in Flash. Having the visual part made it so much easier to explain the Class concept.
I did a video recently on "this" - ua-cam.com/video/eWDXgsIgTGk/v-deo.html
Yea one of the nice things about class is its inheritance of scope. Thanks
Thank you man, you are very talented to explain those concepts... God bless you!
Nice content, nice explanation, I'm a newbie & I could derive a lot of sense out of this. Helpful & v.much to the point.
Clean clear crisp. And your voice is so cool :p
Cheers keep this great work going.
Thanks it made it clear to me that even if it ends up being the same thing, classes makes it more clear that they are tied together.
I do wonder if one way performs better than the other tho but its probably not that important.
There's no performance difference because both syntaxes create the same objects with the same prototypes
@@SteveGriffith-Prof3ssorSt3v3 nice ok thanks for the reply, have a good day
@@SteveGriffith-Prof3ssorSt3v3 Hi, Steve. Loved the video, thank you. I came here with a burning question that perhaps flew over my head. If they're doing the same thing, then what's the point of the redundant syntax and why chose one syntax over of the other?
@@choppinbrixx4931 Trying to make it more declarative. That's what I got out of it anyway.
Thanks for such clear, and concise concepts! Keep up the good work :)
my god finally i understand the difference, Thank you man you saved me.
I get back undefined if i replace this with EmployeeP. I don't understand why. @10:06
let EmployeeP = function(nm, id, salary){
PersonP.call(EmployeeP, nm, id);
this.salary
}
There is a note in the description and in the code gist about a typo on line 50 that needed to be fixed.
@@SteveGriffith-Prof3ssorSt3v3 With the code fix I now get NaN. I'm just confused why I can't substitute "this" for EmployeeP on line 47. Sorry for being noob.
@@nigelbrie5693 Never apologize for learning.
Here is another video where I explain about prototype and `this`. ua-cam.com/video/eWDXgsIgTGk/v-deo.html It should help you.
As an advanced novice JS coder, I always found 'prototypes' confusing ... Your video makes the case for the class paradigm vice prototype model in my view ... Coming from the Java and Python world, classes and subclasses are the way to go and are more OOP than 'prototypes' ...
They both do the same thing internally. Both syntaxes are working with prototypes. The Class syntax was partly added to make the transition easier for people coming from languages like Java. Partly it was yet another attempt at trying to simplify something that has been a confusing mess for 20 years.
Hi Steve,
I am just starting my career in coding and have to say you are like a god of coding for me. I read blogs, excerpts from books, and what not but the way you explain things is just amazing. I am preparing for the MCSA-70-480 exam as a part of my apprenticeship and these tutorials are so helpful for a beginner like me. Just wanted to know if by any chance do you take personal coding classes or any sort of official coding lessons if somebody is interested in learning from you 1-1? My learning at this point in time is exam based and there are so many things that I come across in practice questions that I just can't understand and hence feel the need for proper mentoring for expedited learning.
I teach students, but only in my program at Algonquin College - www.algonquincollege.com/mediaanddesign/program/mobile-application-design-and-development/
I don't do mentoring or one-on-one tutoring. Just no time for it.
@@SteveGriffith-Prof3ssorSt3v3 Yes, I understand. Wish I had a teacher like yourselves in my uni, your students are so lucky :-)
JavaScript Classes and Protototypes beautifully explained. Thanks, Steve
{2023-08-18}
Great Steve.
Cristal clear and you make it easy.
But, what happens if you create a variable without new (i.e: let Jose = PersonP)?
Without the keyword new, any function returns whatever is written after the first return keyword in that function. If the function has no return statement then it returns undefined.
Excellent tutorial, thank you.
Hi, great and clear video, thank you. What is the best option in pratice, classes or closures? Which offers the best performance?
In JS, classes and closures are two different things.
closures in JS are a built-in feature that allows you to maintain reference to a value that would otherwise have been lost, so that you can use it at a later time. Closures will be used both with objects and prototypes as well as with simple functions and loops.
JS classes are a syntactic sugar that lets you define/create Objects and their prototypes with a simplified syntax.
As far as performance between classes and older Object.create syntax, there is no real difference. They both create a JS object and a prototype.
@@SteveGriffith-Prof3ssorSt3v3 Thank you for the answer. Sorry, you are right, my question was between classes or prototypes.
@@fifilulu ok. Well the answer is the same. Classes are just syntactic sugar. They create the exact same prototypes behind the scenes . No difference in performance because they are the same thing
@@SteveGriffith-Prof3ssorSt3v3 Interesting, I noticed that most experienced JS developers prefer prototypes. I concluded it was faster, but it is probably because classes have been lately added to the language.
@@fifilulu you will see a lot more of the class syntax when working with React developers. More experienced developers will be more likely to use the older syntax, like you said the class syntax is newer
I was struggling with 2 things, what a class really is (in JS) & what practical purpose it serves for the work I do.
You have answered that perfectly .. knowing that the class syntax is just syntactic sugar for functions makes my brain happy!
Subscribed.
Thanks
Thank you very much!
Awesome. You made it clear for me, thank you.
Another clear explanation - thank you!
This is fantastic. Are there any advantages of one over the other? Maybe private #variables in classes, for example?
It's just two different syntaxes for the same thing.
Real #private variables are available in classes but you can mimic them with proper scoping and prototypes.
Thank you so much for the very concise information. Sometimes I see projects on Github mixing these techniques (Especially Node.js projects). Why is that? Is there some advantage to mixing these or using one or the other?
Classes are just syntactic sugar for prototypes. In the latest updates to classes there are a couple unique things. But for the most part it is a developer preference on how to write the code. Sometimes it will depend on what else they are doing in the code and if it is more functional or more object oriented.
@@SteveGriffith-Prof3ssorSt3v3 Understood! Thanks so much.
wuauu !!! You made it very easy . A lot of thanks, Blessings
@steve griffith : Hello Steve. This is really Awesome. By far the best Explanation ever. All your Videos are Awesome. Keep Rocking. A Small Clarification, I feel it has to be Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype). [ You have written EmployeeP. This causes an error and I'm not able to call getDetails Function from the Base Class. ] Please do correct me if I'm wrong. Thanks
Yeah. I fixed that in my code sample afterwards. I also have a new video that I did to visually explain prototypes - ua-cam.com/video/01jVgCK-HX4/v-deo.html
Steve Griffith Awesome Man. Thanks
This is such a good explanation, thanks mate.
Why do you need line 50? Where you set prototype? It seems that you can have inheritance just with the PersonP.call line. I imagine I'm missing some inheritance functionality that would be missing but I can't think of it.
There is a note in the description about a change on line 50. The code was changed in the repo too.
Thanks a lot! It's much clear now the concept to me
why arent we able to call - console.log(mary.getDetails()) if the getDetails function was passed to function EmployeeP ?
You can. As long as you changed line 50 to:
Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype);
as mentioned in the description. There was a typo in the video.
is there any difference in which one to use? Perhaps one is faster or something like that? Or are they equal ?
Classes are just a syntactic sugar on top of prototypes. They are equal.
@@SteveGriffith-Prof3ssorSt3v3 thank you
Line no : 50, The setProtoType should be set on EmployeeP's prototype right?
Object.setPrototypeOf(EmployeeFun.prototype,PersonFun.prototype) // extends
The code is updated in the gist and there is a note in the description about this.
Why we don't invoke PersonP function inside PersonP right away instead of using PersonP.call()?
Because call( ) or apply( ) let us indicate what value to use for this inside the PersonP function, not relying on the lexical scope.
I'm still confused between prototype and the hidden property [[Prototype]] that os called by the accessor function __proto__ ?
There are 3 parts to this. 1. The object. 2. The constructor function that made the object. 3. The prototype object.
The function (2) can access the prototype object with the `.prototype` keyword.
The object (1) can access the prototype object with the dunder-proto keyword.
Here is another video I did on the topic - ua-cam.com/video/01jVgCK-HX4/v-deo.html
By using setprototype method, getDetails method of Person's prototype didn't inherited by EmployeeC. So where is the inheritance now? I wrote the same code in my pc but didn't inherited the method by EmployeeC. Plz explain
Did you get type the code that was on the screen or take the updated version from GitHub? If you typed the version on the screen did you read the note in the description about line 50?
With that change, you can add this to the end:
console.log(mary.getDetails());
and it works fine.
@@SteveGriffith-Prof3ssorSt3v3 ohhk sir I got it. Thank u
From what I'm reading, the use of Object.setPrototypeOf() is highly discouraged due to massive performance issues. I also miss how this relates to __proto__ in this very example. Last thing I noticed is that doing SuperClass.call(this, params) is called constructor theft in Nicholas Zakas' excellent book "Principles of object-oriented Javascript", and I wonder if there's any alternatives to that.
Yes. Use Object assign or with the class syntax you can use extends
Excellent tutorial as usual. I was wondering though, why not add getDetails to PersonP like you did with the properties? I.e. this.getDetails = function() { // code block }. This makes the prototype way look more like the class way. I assume they are just different ways of doing the same thing, is that right?
Or there seems to be a difference: the way I mentioned makes 'getDetails' and enumerable property (or method), and using PersonP.prototype.getDetails puts the getDetails method on the PersonP prototype (and anything on the prototype is NOT enumerable). Is that correct?
@@theunknowndev2913 they are different. Classes use actual inheritance and copying methods and properties to the child objects.
Prototypes use delegation
@@SteveGriffith-Prof3ssorSt3v3 Oh, I see. So would I be correct in saying that classes in ES6 are *not* technically syntactic sugar, in that using classes in ES6 copies methods and properties to the child objects using class-based inheritance, whereas instantiating functions uses delegation (aka prototype-based inheritance)? Assuming that syntactic sugar means an easier syntactic way to do the exact same thing.
@@theunknowndev2913 they ARE syntactic sugar. They don't copy the properties to the child objects. Delegation means that the properties stay with the single parent object and the reference to the child is used as 'this' when calling on those properties.
@@SteveGriffith-Prof3ssorSt3v3 I see. I think I understand. This jibes with the fact that classes are syntactic sugar over prototypical inheritance. I mistook the sugar for the delegation, but the sugar is on top of the delegation. Thanks for your help and great content! I will keep learning :).
Awesome video! I have a question regarding the number of functions that can be extended. For instance, EmployeeP extends PersoneP1 and PersoneP2.
You can create a prototype chain that is any length that you need. However, each object's constructor function can only have one prototype. The prototype will be one step in the prototype chain.
If you are asking about combining the properties and methods of a bunch of different objects into a single new object, then you are talking about composition instead of inheritance. ua-cam.com/video/fbpXQ0e8Mp8/v-deo.html
Real stuff starts at 9:25, object.call() is what super is doing; extends is the syntax sugar used to set prototype of child function to be the same as parent function; In this way, all functions in parent become automatically available to child function through prototype mechanism
Nice explanation 👍
Why are methods of a class Person store in Person.prototype and after that we call these methods not passing by prototype ?
JavaScript automatically walks up the prototype type chain looking for shared methods and properties.
ua-cam.com/video/01jVgCK-HX4/v-deo.html
Hi Steve, thanks for this video. I came back to this again after refactoring some code into factory functions and away from classes.
My question is: with what you've shown here, will we still encounter the various pitfalls with 'this'? (ie. having to bind explicitly when invoked from another function -- my intuition says yes because this illustrates an alternate syntax for the same end result).
To that end, would you recommend a more functional / composition based approach where factory functions return objects with certain properties and then object types are returned by composing those functions?
Cheers!
With JS I would definitely recommend using a functional / composition approach to building things. Classes in JS are not what you expect from "class" in other languages. It is a nice clean syntax if you are building objects that will have a limited scope and interactions with other object types. However, when architecting anything in JS you need to think in terms of prototypes and composition works better there.
hi just wanted to know doesn't it breaks linkage with Function.prototype with EmployeeP ?
I guess instead
"Object.setPrototypeOf(EmployeeP, PersonP.prototype)"
we should use
"Object.setPrototypeOf(EmployeeP.prototype, PersonP.prototype)"
That edit is in the description and was changed in the source code in the Gist.
At line 47 PersonP.call(this, nm, id) is there any other way to write it using the setPrototypeOf or Object create method?
Thank you very much for your tutorial. Amazing as always!
We need to call the PersonP constructor to give us the name and id properties and their values.
setPrototypeOf is just creating the prototype chain for inheritance.
It is like calling super( ) inside the Class syntax's constructor( ) method.
Very well explained. I will be hitting subscribe.
Awesome explanation! Now I'm wondering if having the "class" keyword in JS makes things more confusing.
In some ways it does. But if you understand how the prototype system works then you just need to learn how the class keyword works with this. Just don't try to force your understanding of `class` from other languages into JS.
Instead of setPrototypeOf we could have also used Object.ceate() right?
Absolutely.
Object.create( ) and Object.assign( ) were intended to replace the setPrototypeOf method.
@@SteveGriffith-Prof3ssorSt3v3 Thanks for taking time out and replying. Your voice is so assuring.
As a new JS coder learning ES6, and planning to transpile for backwards compatibility, is there any reason for me to learn the non-class style?
As we discussed in the GitHub comments, this response is more for other people interested in the answer.
Most of what makes up ES6+ are additions to the language, not replacements. We have options on how we write our code - a functional style or an event-driven style or an object oriented style... or a blend of those. ES6+ gives us options.
ES6+ is not invalidating any code that currently exists. The browsers still support all the JS going back to the late 90s. (few very minor browser specific exceptions).
When it comes to creating Objects and their prototypes you get to choose which style/approach that you want to use.
If you are starting out, pick one. Learn it well.
But you also need to learn what is going on behind the scenes with that syntax. Eventually, you will need to learn the other syntaxes and how they relate to one another.
Almost all developers have to work with other developers. We're a stubborn and opinionated bunch. Teams need to agree on a style for how code is written and Objects are created. Even if you are transpiling your JS for backward-compatibility in the browser, your team mates need to be able to read and work with your code. Sometimes you will be lucky and get a team that all like the same style and approach. Other times you will need to adapt.
JS is a journey. You will never stop learning. The language continues to grow and adapt. That can be scary but it is also exciting.
@@SteveGriffith-Prof3ssorSt3v3 Point taken. But i must say, i think it's a perfectly fine idea, as a way to get new coders started off on the right foot, for a new learner to start with ES6+, and then add "oh by the way, here's the old style in case you come accost it."
Cuz i think it's easy for new coders to get overwhelmed, and not get a clear emphasis on what's the new standard vs outdated ways.
@@johnywhy4679 This is a great point. As a newcomer to JS, the burning question in my mind the whole time was..."which one should I use for best practice"
I read other comments that it's just syntactical sugar, but I also read stuff that suggests object.assign vs spread syntax is much slower. I'm probably not comparing apples to apples here, so forgive me but it's the type of stuff that twists me up sometimes.
VERY NICE..... Easy to understand.
To me, it feels like Typescript interfaces and type aliases can do all the things that you would use classes/prototypes to do. I feel like i might be wrong about this. Does anybody know anything about this?
Typescript is a superset of ECMAScript... which is JavaScript. It just has extra support for things like primitive datatypes that are strongly typed, intefaces, enums, an extra scope level, etc.
End of the day it still has JS under the hood with prototypes.
It should be:
Object.setPrototypeOf(EmployeeP.prototype, PersonP.protoype)
With code shown in video, you're effectively attaching the employeeInfo() method to PersonP prototype, meaning even PersonP instances would have that method after that point.
Yes. There is a note in the description about that typo. It was fixed in the gist.
Thank you so much, you explained it really well.
thank you! what does :: mean?
It is just a text separator between the name and id.
When to use class syntax and when to use prototype syntax?
It's all prototypes really. So, there is no performance difference. Just a personal choice as long as you understand how the prototypes are created and used.
What is role of supee(nm,id)
Really good explanation
thank you
it' s a really good one
thank u!! React.js not using Class right? they use behind scenes things as u show in the vid?
You can write React JS apps with or without the JavaScript class syntax. A lot of what you do in React will typically be with the class syntax. Just keep in mind that behind everything it is always prototypes, not real classes.
@@SteveGriffith-Prof3ssorSt3v3 thank u! really I got confused with prototypes, I understand it but I can't write my whole app with it.
@@SteveGriffith-Prof3ssorSt3v3 I prefer functional components, therefore... functions.
Is there a way I can increment using a variable with this? For example: this.variableName++;
I'm trying to do it and the system gives me an error of "cannot read property of undefined".
I've been googling and applying some other things like this.variableName = this.variableName + 1; but doesn't work.
Thank you for all the help, Steve. Your explanations are the best.
Yes you can have variables that are associated with an instance of the class/object. The way you write the code to increment really depends on how you write the object factory / constructor / class constructor.
In the class example I had at the start of this video, if I had a method like this:
add() {
this.id++
}
If would be incrementing the value of id inside the object created by calling
new PersonC("Bob", 123);
So, this code:
let bob = new PersonC("Bob", 123);
bob.add( );
would increment bob's id to 124.
Here is a code sample of a class that has a static method which will increment through possible values for instance id values. The id param for the constructor is optional. If you pass it then it will validate that the number is not used. If it is then it finds the next available id.
gist.github.com/prof3ssorSt3v3/ff1716453c0858b77cf1f0a652c90ea8
@@SteveGriffith-Prof3ssorSt3v3 You helped me a lot. :)
And I'm following you on github now. Thank you!
Another very cool tutorial!
Its actually Prototype, classes don’t exist in JS. Also, this is “this”. And its also an Object
Gold! Incredible! Thank you!
What happens when you dont put the 'new' keyword there? Im talking about this: let fred = PersonP()
`new` changes the return value of any function - ua-cam.com/video/I2CdrKlPdAY/v-deo.html
Hi, Steve good explanation, but I wonder, can PersonC get salary method from Employee as the will have a link between them or it is allowed only for Employee as its prototype is PersonC
Your suggestions???
Thanks in advance!!!
I assume that you are asking about EmployeeC. salary is a property inside of EmployeeC. EmployeeC extends PersonC, which means that the CmployeeC type objects have access to things from inside of PersonC, not the other way around.
@@SteveGriffith-Prof3ssorSt3v3 Ok Employee type have an access to the elements inside PersonC ,but what about opposite version, can PersonC have an access to things inside Employee
thanks for this video man. It really helped a lot.