Class keyword – Object Creation in JavaScript P7 – Fun Fun Function


Good Monday morning Today we are going to look at the class keyword in JavaScript This video contains 3 segments The first one is “‘How does ‘class’ work in JavaScript?”‘ This video talks about how a ‘class’ works specifically in JavaScript so I’m going to assume that you know what a class is in the general sense The second part of the video deals with the fact that JavaScript does not have classes I’m going to demonstrate how the class keyword is just syntactic sugar on top of the prototypal inheritance model The third, and final, part of this video is called “When in Rome, learn JavaScript” In this segment I’m going to try to convince you, if you are new to JavaScript, and you’re coming from another programming language such as Java or C# or whatever to learn JavaScript properly and not try to force your existing mental model into JavaScript because that will just cause you pain That is what we are going to talk about today I am MPJ and you are watching Fun Fun Function Before we begin I would like to stress that this episode is part of a series The purpose of this series is to really get into and understand how object creation in JavaScript works, learn it properly because we’re programming in this language now we should really learn its nooks and crannies If you found this video by Googling ‘JavaScript Classes’ it’s very tempting to just watch this video and try to get on with it but please look at the series from the start instead you can find it by clicking in the upper right corner or the link in the episode description this will make you feel a lot less confused by having the fundamentals down it will make you a calmer person and a better person and you will thank me for it, I promise If you are not a new viewer however you might be confused as to why I’m doing an object creation series because I started this channel by doing a series of how to do functional programming in JavaScript and I’m often vocal against doing too much object orientation You should not necessarily view this series as an endorsement of object orientation but instead view it as a way of getting to know JavaScript intimately because dismissing something because you know it and you’re well familiar with it and you choose not to use it, that’s wisdom but if you don’t know about something you don’t know it fully and you don’t know how to use it and you avoid it then that is not wisdom, that is just ignorance Alright, let’s get into it So classes in JavaScript they work very much like you would expect Lets create a class called Mammal er, there yeah and then we are going to create a new Mammal call it with nothing and just call it ‘fluffykins’ hello there and lets echo out what fluffykins is let’s check what it is, oh it’s an empty object If you are interested, the plugin that I’m using for inline evaluation here is called Quokka You can find a link in the episode description Classes in JavaScript can have constructors as you would expect them to have and you can also assign properties to objects like this dot, let’s call this property sound you can assign it and … let’s see I want this to use an argument so constructors can have arguments so let’s call this ‘sound’ and then we also need to pass it, down here I’m goint to call this ‘woof!’ … there so the property ‘sound’ of fluffykins is now ‘woof!’ nothing strange here You can also do methods so you perhaps call this ‘talk()’ and it will just return whatever is inside ‘this.sound’ so if I do ‘fluffykins.talk()’ nothing happens I need to return ‘this.sound’ and this does not work either because I need to assign it to a variable or Quokka won’t evaluate it woof! … woof! woof! woof! woof! woof! I really should think of better examples than animals but I like animals, they’re cute and nice and, of course, classes in JavaScript can do inheritence so let’s do class Dog extends Mammal and we’re going to give it a constructor it will take no arguments and it’s going to call super which is basically calling the constructor of the inherited class so ‘super()’ here is actually going to call the constructor of Mammal here because we are inheriting Mammal so we are going to pass in sound here lets call this ‘woffeliwofffffffffffffffffff’ and let’s change fluffykins to be a Dog and remove this and see if this works Did it work? Why doesn’t it work? Let’s open the terminal ‘super’ keyword unexpected here? What is happening? Arghh! Oh, it’s because I’m typing ‘contructor’ It’s constructor. There. Now it works. Woffeli-woffeli-woffeli-woffffffffffffffffff I am the best at programming. I would like to make a side warning here we are seeing some inhertance here Be very careful about using inheritance It’s very problematic. It’s a problematic pattern and you should prefer composition in almost all cases You might want to look at my video ‘Composition over Inheritance’ by clicking in the upper right corner or in the episode description But that’s a side note We’re not passing judgement on that right now. I am very, very bright Perhaps I should drop the thing. Let’s drop the thing. Perhaps this is better. Yeah, that’s better. So far the class keyword in JavaScript works like we’d expect if we are coming from a Java or C# background or any other programming language, mostly, that has classes but there are weird things that work not like you’d expect For example, there is no way for us to make this sound property here private So there is no way for me to say something like ‘private sound’ There is no such thing and there is no trick to do it either So I can always do let me show you let y=fluffykins.sound and I can do y … you see I can access it from outside and I can also change it so let’s say I can call it ‘fluffykins=1’ No, sorry, ‘fluffykins.sound’ and now it says 1 or I can just go ‘meow’, you see Since private members do not exist in JavaScript you often see people doing underscore as a convention to indicate that this is a private member and that you should not mess with it if you are using the class but, you know, I can still just mess with it It’s very brittle At this point you might be asking yourself why doesn’t the class keyword in JavaScript have support for private members? It seems weird because the class keyword was added very recently to Javascript it was added just a few years ago Why didn’t they add this? It seems like a very basic type of functionality That’s a great question and the answer is that JavaScript does NOT have classes! It’s all fake In the previous episode about the new keyword we talked about how JavaScript fakes classes In that episode we looked at how the new keyword could be applied to a constructor function and together with the prototype that kind of fakes something that behaves just like a class But it wasn’t really a class It was just kind of, sort of, looking like a class And the class keyword in ES6 is really just like that it’s just a bit prettier syntactic sugar It’s all smoke and mirrors Allow me to demonstrate I’m going to do this ‘typeof Dog’ It’s a function. No, it’s a function because classes do not exist in JavaScript It’s just a thin layer on top of the old prototypal inheritance It just looks a little bit prettier So let’s see if I can just do Dog.prototype.talk There we have our talk method It’s this one here And if I just call this immediately we are going to get an error No, not an error but undefined because it doesn’t have a ‘this.sound’ property Let’s see if we can … I’m going to do something now if you understand it that will yield you a golden star because I’m going to be using all of the things that we have been learning in this series so far talk.bind and we are going to bind it to a new ‘this’ The first argument to bind is redefining ‘this’ and we’re going to call it … be an object with the property sound and we’re going to call it err… err.. err … hmmm it’s hard to invent… sound… let’s call it ‘ROAR’ and then we call that function and then it goes ‘ROAR’ So what just happened there is that we called bind with this object here an object with the property ‘_sound’ and that means that what bind does is that it creates a new version of ‘talk()’ where we have bound ‘this’ to be this object here so it creates a new function and returns it and then we call it here with this And also I think I can do this actually Dog.prototype.isPrototypeOf(fluffykins) Yes. True. So you see, class is just a very thin layer on top of the prototypal inheritance There is no class based inheritance in JavaScript It’s all just smoke and mirrors So the class keyword has basically been welded onto JavaScript because there was a lot of pressure to do it and the reason that there was a lot of pressure to do it is that there’s a lot of new programmers coming into JavaScipt not new programmers as in newbies but new programmers from other backgrounds C#, C++, Java Programmers are coming in that are used to languages that are, (a) heavily object oriented and (b) they have a classical inheritance model they are class based so they’re very used to this and they don’t want to learn the prototypal inheritance model that JavaScript has and they don’t want to learn the functional programming model that JavaScript has They want JavaScript to be like the programming language that they already know And I don’t want to fault people for that too much because looking up how to do a class was one of the first thing I did when I started learning JavaScript In my mind adding the class keyword to JavaScript was a little bit like … I might get in trouble for this … giving clean needles to meth addicts It is a distinct improvement over using dirty needles to do meth but if we can we should try to get people off meth Which bring me to the third segment When in Rome, write JavaScript Try to embrace JavaScript and its strengths and learn to write JavaScript in a way that is natural to JavaSctipt Do not try to force the existing models that you have from whatever language, Java or C# into JavaScript And the reason you want to do that is that if you don’t you will always have this sense of unease and uncertainty about what is happening When you are looking in the Chrome inspector and you see these prototype things with underscores on your classes you will just feel… what is this?… oh I don’t …urgh You will just feel not at ease because you don’t understand what it is that you are doing Because you are using this thing that is kind of looks like a class but it really is trying to hide some internal implementation from you but it does a bad job of it so it just gives you this weird sense of I don’t have control And if you don’t understand the prototypal inhertance model and that class is just a thin layer on top of it you will not understand its limitations You won’t understand why there is not such thing as private members and you will just be angry about that limitation but you won’t understand the context about the thing that you’re angry about and that will give you a sense of not being in control and the world is against you And this is not just about learning about the prototypal inheritance model of JavaScript its also about learning about the functional nature of JavaScript because that ties into object creation in JavaScript a lot because there is a lot of wierdness with ‘bind’ and ‘this’ that you won’t really understand without understanding the functional nature of JavaScript So if you want to feel comfortable writing JavaScript, and know really what you’re doing you should check out this series from the start if you haven’t already and you should also check out the my functional programming in JavaScript series because that will… that ties into object creation a lot That is it for today We talked a little bit about how a class works in JavaScript then we explored how JavaScript doesn’t have classes and finally I ranted a little bit about how When in Rome, write JavaScript If anything was unclear or you would like an elaboration please write a comment down below and I will try to answer it You have just watched an episode of Fun Fun Function I release these every Monday morning 08:00 GMT If you don’t want to wait until next Monday you can check out this episode that Google’s machine learning thing-a-ma-bob has selected for your viewing pleasure I am MPJ Until next Monday morning, stay curious

About the author

Comments

  1. Don't forget to mention a python like solution to multiple inheritance. 🙂
    Raymond Hettinger – Super considered super! – PyCon 2015
    Video: https://www.youtube.com/watch?v=EiOglTERPEo
    Article: https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

  2. javascript has private members. Here's an example I wrote using the class keyword. Give it a try.

    class PrivateTest
    {
    constructor()
    {
    // Use var to make a private member variable
    var privateVariable = 123;

    // Define a function here in the constructor to make a private function
    // This function can call other private members
    function privateFunction()
    {
    console.log(`test: privateVar = ${privateVariable}`);
    }

    // This public function defined in the constructor can reference private members
    this.publicFunction = function()
    {
    privateFunction();
    privateVariable = 234;
    privateFunction();
    }
    }

    // This public function CAN'T reference private members
    anotherPublicFunction()
    {
    }
    }

    var privateTest = new PrivateTest;
    privateTest.publicFunction();

  3. JS has no class.

    I just remembering figuring out at some point; classes, yeah don't do that. Thanks for making it more clear as to why.

  4. Reminds me of Ramda.js trying to bring currying into JS. Or, basically, ML style programming into JS. Although I really like it, it really isn't traditional JS. At the same time though they do make it more JS-like rather than bringing a strict interpretation of other languages into JS.

    So, the OO guys do it and the functional crowd does it. I lean towards the functional crowd, so JS overlords, please bring us native currying!

  5. where did the name fun fun function come from ? im always thinking about someone stuttering while trying to say function lol

    and yes I know that its about fun and not stuttering

  6. Why is JS still trying to imitate Java? New learners should deal with the new paradigm of the language. This "syntactic sugar" doesn't even help them learning JS properly. JS should finally get rid of "Java" and change its name back to LiveScript.

  7. Would it have been more palatable to call it something else? It doesn't seem to have many real problems with how it works, more just the word "class" being potentially confusing.

    The exceptions are private and protected members, but those aren't difficult to implement in the module pattern and it's not like you lose the legibility of "class." Classes are generally used on export.

  8. This "clean needles" metaphor made me laugh so hard. What a great way to phrase that idea. It's almost like the committee was scheming saying "no, no come to JavaScript. It's a wonderful language. See, we even have classes". But the best part of your phrasing was aligning class inheritance to meth hahaha Best things I've heard in a while! Keep up the great work!

  9. QuokkaJS is cool but have you ever heard of js-playgrounds? (npm install –global js-playgrounds)

  10. What are your thoughts on languages that compile down into JavaScript like TypeScript or CoffeeScript? (Especially as TypeScript is used for Angular now)

  11. hello ur channel is so amazing i like the why you talk about programming even if i don't understand any thing hhhh i have i rec west i startes learning HTML/CSS this is my first week of learning journey can u please please give a beginners like me an advice please ….i hope that u make video for beginners about learning and some advice please please please

  12. I really want a mug that has that yellow strip with the words "When in Rome learn JavaScript" on it.

  13. Hi, thank you for your informative and funny videos, I'd like to ask you what websites do you visit daily to learn something about JavaScript, do you have a few or there are a lot of them? I get stuck learning really quickly because there are so much info about JS that I don't know if one website is better than the other and how to know if provided content is high quality? Any suggestions?

  14. Please come out with some udemy courses on ES6, functional JavaScript, react etc. I will buy them all

  15. This ES6 syntax is great for "newbies" to Javascript that are actually experienced in Java/C++ etc. But what about for actual newbies like myself who are learning Javascript as a first language. I got my head around ES5 and prototypal inheritance and now I'm expected to learn both ways of thinking to accommodate "Experienced" programmers who apparently can't do the same thing. And it's not even optional. I won't be able to get a job without doing it. Thanks professionals for not being able to do what a 2 month newbie now has to do. You guys so smart!

  16. Awesome explanation! Thank you so much!

    Which IDE are you using? I love that it shows you what the variables will evaluate to directly in the IDE. Is that a package or plugin for an IDE?

  17. I got the golden star as I guessed the talk.bind before you even started hinting or maybe started writing Dog.prototype.talk. Ummm..what can be be possibly doing with it ?

    Hehe.

    But yes, no specific use of class keyword without private property and all that etc. Liked the re-inforcement of "classes do not exist/ or are fake".

    Gotta watch Composition over inheritance for Wisdom. Waiting how it differs from prototypical inheritance which purely makes sense.

    However, I got super() first time since the recent inception of React learning.:D

  18. "This video… oh my god. I just found f***ing gold."
    This topic has been entirely confusing to me for almost a year now, which is to say 'since I started learning Javascript'
    Thank you, mpj.

  19. I used to be pro-class-keyword when I first learned about it, having come from a Java background. I thought: "This will make things more organized! Woot!" But as time went on and I began learning more JS, it started to feel very constricting and boilerplatey.

  20. This series was very useful, but I feel the videos are too bloated. You repeat yourself too much and the content could be condensed a bit more.

  21. I had been reading the documentation for JS classes and just couldn't wrap my head around `super()` for some reason. Thanks for explaining it so succinctly and clearly – that super() is effectively the constructor of the inherited classes – and arguments passed into it are passed as into that constructor!

  22. MPJME, we are both wearing same glass frames 🙂 secondly you are giving me heart attack, i am starting hating classes, although i never used it in js so far, i use function objects. You have made me rethinking in every aspect of JS programming.

  23. I'm find it pretty confusing that methods in classes aren't separated by semicolons, like properties in standard objects. It hurts when you forget to place semicolons in objects and now it hurts just as much when you 'recall' to use them inside a class.

  24. What I don't understand is why so many modern libraries seem to lean on constructors and classes, even when employing functional concepts, factories, etc. Somewhere along the line, usually as the single top level access to the api, or the actual thing that you require from the the NPM package, there it is, an uppercased (by convention) function you need to use new with.

    Maybe it's because fluent api's are (arguably) slightly easier (or harder) to write with classes, I don't know — but every time I try to figure it out, my deep fear of new, class, and this seems to grow only deeper. I feel less alone when I watch these videos.

    But at some point I am going to fail a job interview though, because I cant remember the difference in this binding between arrow functions and function functions and lexical variable descriptors, and I am going to blame you for reaffirming my suspicions that closure makes it all moot.

  25. Thank you for a wonderful explanation. Finally, i do feel relieved. That 'class' keyword has been really bothering me and now I'm happy to know that it's actually just a sugar keyword for basic prototypal inheritance.

  26. class is not syntactic sugar, extends is deeply magical in that it is the only way to create instances that are callable. theres no other way to create a class C such that (new C)() doesnt throw exception that its not a function. so much for javascript is a functional language(everything is a callable) .

  27. I come from OOP background and I think that whoever designed Javascript must have escaped from a mental asylum

  28. i am backend developer with node and i want to know that why we follow object oriented programing in javascript what are its advanteg

  29. class Foo {}

    var myFoo = new Foo()
    console.log(myFoo)

    // is printing out: Foo {}
    // instead of: {}

    why?

  30. I realize this video is really old, but I'm curious — if you're so against classes/OOP in Javascript, then what do you think of React and its Component classes, for example?

  31. @mpj or anyone who can help. React uses classes for every component that you make extending React.Component. Is it losing speed or performance for using the "inheritance" and "class" keyword?

  32. I used to understand classes in js, but then I looked up self object in js, and in stead of that, this was all yt had to offer. so I thought, fine, I'll watch it. now I have no idea what classes in js are, and still don't know a thing about self object…

  33. All this is of course super cool but can you please show real world examples )) Mb some cool stuff from Spotify ) And of course thank you for your Work

  34. It is very fortunate at least for someone like me, that JavaScript does not have class and we are not forced to read those kinds of codes.

  35. Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

  36. terrible instructor. can't focus on the code because he's barking and making everything to get some attention as a little child instead of focusing what really matters.

  37. great video, as always. i do have a problem with the meth analogy, as needle programs are actually extremely helpful to get people out of meth, and it seemed like you implied that they're a bad thing, and i don't really agree with that.

    still just a detail that has nothing to do with the actual subject of the video, but i still felt like i should point it out

  38. I'm trying to pass an object that I created using this method and the variables are changed, but the variables for the object always reset when the object is used again.

  39. UPDATE! Private class fields coming soon.
    More about it:
    https://developers.google.com/web/updates/2018/12/class-fields

    In short, now fields in classes can have # hash before their name, making them private, and not accesable from anywhere else than the class itself.

  40. As a beginner I've noticed one irritating tendency amongst all youtuber geeks -"wannabe funny guys"!
    Leave it, it's UNNECESSARY!

  41. You look and joke like Johnny Depp I swear, please make new content about JS for beginners + and elements that gives us headache.

  42. Im starting with javascript but i dont get when apply class in my regular website. In practice i can apply class animal and make objects like dog, cat or bear. But in a job website i dont know how to apply classes.

  43. I'm kind of doing the opposite. I am a JS beginner, and this idea was fed into me that classical inheritance is bad, by Medium articles by Eric Elliot (i hear he is notorious, but I have no idea if that is the case). So I really became focussed about learning prototypes well (at least it led to something fruitful, eh?), and now that I have a somewhat decent idea of it, it's still quite new for me and I don't wanna confuse myself and ruin my weeks (2 at least) of hard work by trying to understand classes in JS.

    So I think I will completely avoid classes for nor, and make do with the old school of using prototypes until I am comfortable with those fully. Then I will move onto classes. So, after covering 6 of the 7 videos on this series, I will pause here, and leave without watching the last one. Hopefully, I will be back before long, when its time, and then finally watch this, and add another tool to my arsenal. Happy learning folks :3

Leave a Reply

Your email address will not be published. Required fields are marked *