@@ThePrimeTimeagen accurate text selection is the final frontier in software accessibility and your blazing the path by showing full-bookending is a fools gamble!
JavaScript is the MOST object oriented language. EVERYTHING is an object. It just doesn't have real classes (blueprints for objects), it has prototypes, which are OBJECTS. The Class keyword is just there to make it easier to understand, and it makes perfect sense to work that way. In the end, it's the same.
Javascript's objects are an implementation detail, not a feature. saying javascript is object oriented because everything is an object s like saying python is a C-oriented programming language because everything is a C library. The average python programmer thinks C is the third letter of the alphabet and doesn't need to know better. That's like saying carpenter is a clay oriented craft just because your neighbor happens to be a carpenter and their workshop is made out of stone. As an afterthought feature, Javascript's objects are horrendously bad. The class keyword doesn't help understanding at all, pretty much the opposite. It helps usage, not understanding. It is there for OOP bros who don't even know their own paradigm and couldn't use prototypes to save their life. And I don't blame them, JS is a pretty bad place to learn about prototypes. Every now and then one of em asks a question which boils down to "why does my class not behave like a class", and the answer is simply: "because it's not a class", it's a prototype cosplaying as such. The implementation of classes as an afterthought in JavaScript occurred over several iterations at least twice independently (Typescript). For example, I can't think of any object oriented language with 4 standard competing ways to do encapsulation, and no that's not a quality.
@@danvilela This is the way! The more complex your code is, the more secure your job becomes and the more money you can demand from that company, because their business won't survive without someone understanding that "high quality and elegant" code :D At least until ChatGPT becomes better.
The article is a classic case of rationalization. The author started of with a conclusion and then went searching for arguments to support it, but failed to find any arguments that would support his conclusion or really make any sense at all.
@@tc2241 no. they're just saying that there are better abstractions out there. the author of the article could've referred to closures as a better alternative to objects and classes, but he's just a boomer stuck on ES5 lol
I have a colleague at work trying to create classes for everything and apply design patterns everywhere even for simple logic or single line of code. It adds a LOT of abstraction for nothing making it harder to debug. And if you tell him it may be not necessary, he will look down on you for not respecting OOP / Design patterns as taught at school. 😅 Sometimes I wish we would see more KISS in code nowadays.
This is a typical mistake beginners do when first learning OOP. After learning a new design pattern they feel the need to apply it to all of their codebase and completely ignoring any common sense. When it comes to design patters, less is often more.
Javascript objects are not 'just maps' , chromium actually creates c++ structs to improve performance. It's extremely complicated and the compiler does a lot of smart things in the background.
see, that'd be actually useful information, if the article actually was investigating the thing it purported to investigate. it's just a weird crappy opinion piece.
The article says that JS Classes are just "Syntactic sugar" . We should use them more then. Having more readable code with barely any impact to performance is great. (Like with anything in life, that involves sugar, you should not over do it though.)
Edit: article is from 2020, private attributes were not widely available back then. :) Private attributes exist in JS, see "Private class features" on MDN. (something the author of the article could've easily looked up before stating something wrong) Also that "Classes are the same as in ES5" because if you transpile it to ES5 with Babel... was quite dumb :D TL;DR: Just use JDSL.
At the time the article was posted private fields were not widely supported in browsers. Firefox got the feature over a year later (according to caniuse). I agree that it would have been nice for them to say that it was being worked on, though.
Programmers never stop to amaze me. When a normal person in their work environment doesn't see something useful they won't go online and write an article "Stop using something". But I have seen countless articles or videos of programmers saying "don't use classes, don't use else statements, don't have methods longer than 5 lines of code, don't use a for loop etc etc..." and will give you a few examples that fit their narrative. I can think of dozens of examples where they are useful and also as many where they shouldn't be used.
I saw a “It’s time to say goodbye to Bootstrap” a couple of months ago. I actually read it and as you can guess it was garbage. Just a bunch of “we have tailwind!” And “css is modern” like bootstrap is not constantly taking advantage of new css features At the end of the day, the message is “just be normal” lol. If you dont like bootstrap, sure, talk about it. But dont pretend like you have arrived to a revolutionary “truth” lol
Isn't OOP a concept and not something language specific? C has no concept of clases/objects, but you still can implement OOP with structs, functions and pointers etc
@oodevr I believe it is nested function definitions whose top-level function returns a bucket object containing the top level function locals and the nested functions. It's cute but a cluster**** in terms of performance. People have dogmatic prejudice against classes.
@@damienlmooreit at least used to be that it was faster than classes, that's why typescript itself is written that way. It currently seems to be slower a lot of the time, but if you unwrap the actual allocations and lookup logic involved, that's not actually necessarily true, they're just missing some fast paths that classes have. The trade off for not having the semantic clarity of the class syntax is that without using "this", you can much more easily grab a function and call it without using .bind() or .call(), you can have much more natural multiple or private constructors, and without instanceof you can swap it out for tests far more easily. But I've used both, and you can mix them pretty easily, especially with Typescript interfaces. I mostly just wish Typescript didn't default the this parameter to any.
@oodevr I... can't figure out what you're actually asking? I didn't say that using "this" was slower than scope lookup, I said it at least used to be. As in they've put a lot of work into v8 to make classes less abysmally slow, and now they're mostly just really fast. I also said that there's not really any real reason for scopes to be slower, which I meant to imply that they currently can be slower, but that that could be fixed. There's not really much in it either way unless you're doing things you shouldn't be doing either way, like allocating a million vectors as objects.
@oodevr just checking: you're aware that JavaScript performance changes, as the implementation has work done on it, right? The v8 blog has lots of examples where using some new feature was something like 50 times (not percent!) slower than some earlier equivalent until they made a fix. Don't pay too much attention to performance numbers without specifically measuring, and don't pay much attention to micro-benchmarks (it's stupidly hard to benchmark JavaScript accurately), and don't keep assumptions about performance around for too long either, as things are fixed. For example, are you aware that let and const still have something like 10-20% performance impact in real workloads over var, for example? You'd think it wouldn't make any difference, but it absolutely can (sometimes!), and it might not in the future, as I think it's being looked at right now. The reason I prefer avoiding classes is that it's simpler to think about JavaScript without using "this", not performance. I don't know why you're picking on that point.
"Don't use classes, use something that's less optimized to do the same thing, or just make something objectively more difficult to maintain. Also, classes are less optimized because trust me bro."
I love the argument "Because react devs told you not to use classes" This guy seems severely confused what the difference is between a React class component and a JS class. If you don't understand why the react devs moved away from class components, don't write an article mentioning this as an argument against classes. This is so dumb.
Modern browsers are able to compile a lot of JS to native behind the scenes on the fly, but that is only really effective if you use classes, otherwise you'd need to hit the same object that did not change over and over again before the JIT bothers.
One reason prototypal OO is more powerful, as far as I understand, is because you can do stuff like building/binding a missing "method" at runtime. In theory there is no limit of complexity in the inheritance scheme you can mimic. It's not necessarily better, it harder to optimise, but it's more powerful. That being said, I like neither style of OO in JS. For very simple stuff, classes feel like an unnecessary abstraction. For more complex patterns, JS doesn't hide well the prototypes under the hood. And Prototypal syntax in JS is really ugly. And then there is the lack of operator overload, the lack of a type system and the lack of static dispatch, so OO in JS is really just glorified namespace, possibly with some ugly inheritance and poor interfacing. It has no synergy with other feature whatsoever that most other OO language have, baring iteration. Lua IMO is prototypal OO done right. The approach is extremely minimalist, the syntax is very simple, and you code exactly what you need from OO, nothing more. The downside is you have to code it yourself, but come on, having to code in lua is more of an upside.
JS has always been a powerful lang in all the wrong ways. Prototypical OO doesn't add anything useful to the table and its patterns can be replicated using far better abstractions. Every now and then there's a prototype-related vulnerability in V8 that wouldn't exist had JS been any saner to implement and develop with. JS should've had multiple dispatch like Julia imo. At least that seems to be much truer to the aggressive late-binding early OOP advocated.
Hehe, prototypal OO allows you to implement extension methods, like in C#. It is a little over the hand, and the syntax sucks, but after you put up the scaffold it goes pretty smooth
If only that were more true for JavaScript. VS Code and Visual Studio do a decent job but when you start passing class instances as arguments they get totally stupid. Luckily there is a silly but mostly harmless work-around: Add a line of code to your class constructor that checks if the constructor's first parameter is an instance of the class itself and simply return it if so. Then whenever you have a function that wants to accept an argument of that class, reconstruct it at the beginning (e.g. arg1 = new className(arg1)). That's enough to make VS Code and Visual Studio remember the class properties again and give you the correct code completion.
JavaScript's OOP style was taken from Self, a language by Sun that took its syntax from Smalltalk, but switched to a new (at the time) prototype based OOP. There was a simple transpiler from Smalltalk to Self, so existing code could be used. NewtonScript for the Apple Newton was based on Self even more so than JavaScript was. JavaScript is more OOP (by the definition of "closer to Smalltalk") than C++ is. Classes actually are different, by the way. Try making an AudioWorklet using prototypes to see what I mean.
FP multiple dispatch functions may act like class methods (if they are dispatched on first argument alone), but they do not work like OOP methods. The reason is, if you know argument types, you know a method and can resolve it at compile time (even in dynamic language like Julia!). this means that dispatching can be implicitly made static most of the time, and when it is dynamic, it still should match one function with one argument collection. dispatch functions also do not feel like class methods, they feel like dynamic pattern matching statements, if that makes sense. so your program looks like one giant function, cut into match statement arms.
5:16, yes, recreate it with closures. Factories that return the methods you want that operate on private enclosed values is always a better experience than classes in JavaScript in my opinion. They used to call it the "module pattern" and it is somewhat similar to commonjs modules
Ah yes, the IIFE closure returning a public interface :-) I used this pattern extensively past and honestly liked it too, but the minute we had support for native classes I dropped it. I just don’t see the downsides of classes - at least not the way I use them.
@@JensRoland I pretty much exclusively write code for a browser and rarely find the need for anything oop-like, so maybe that's why I don't really use them. Then again I might be stuck in the past a bit too much. Last month I used setTimeout to break a long running fuzzy search algorithm up and prevent it from blocking and make it cancellable. When I was looking at my code after I was done I realized I should have just used a web worker.
@@JensRoland the native classes have no downsides, especially now that you have fully private members. The IIFE closure instead is a bitch and eats a lot of memory
While I don't always reach for classes, this "article" just contains a bunch of assumptions with no real explanation behind their reasoning; no digging into JS engine code, like V8 or JavaScriptCore, to see if what they claim holds true at all. To me it's a bunch of baloney until you can actually prove what you're claiming is true. The only well known fact is that classes are syntatic sugar over prototypes in JS, though. I also highly encourage anyone to read V8 team's article on hidden classes, which are an optimization mechanism for prototypical objects (created through `new` keyword).
People that say OOP (or any other paradigm) is dying or fundamentally bad, or for that matter is the one true way to work, are just outing their lack of experience/ knowledge. But it's always fun to poke them in public to demonstrate that.
i have seen some gnarly functional components that dance around being stateless when state is actually needed for the application to function. its mainly functional programming pseudointellectuals trying to fit a round peg in a stateless hole
Isn't this just one of those things where classes aren't the actual problem but people just not knowing how to use classes and following OOP principles sensibly is? Inheritance to me is a great example where I think people shoehorn methods into parent classes that don't belong there as behaviors of the class objects instead of creating a function that takes an object as a parameter, get some data from that object, and then acts on it. Or vice versa where people are afraid to use a class so they define functions that need like 6 parameters do do a thing instead of just writing a class method to a class that already has access to some or all of the data where the behavior would make sense.
Another banger video. If you want to encapsulate state and methods in JS you can simply put them all in an object. So here he's indirectly referring to using Object.create to wire this type of thing up to a prototype in JS if you want the methods/properties only once in memory - on the base object. Object.create is the newer syntax for using __prototype__, etc. This would have been an idiomatic way to add to and access the prototype in JS, but it's not used very much since everyone learns Class syntax from other languages and it's more familiar. It gives performance/memory boost but it's only practical if there are more than 10k instances, you aren't changing the data structure much if at all, and it's a shallow object. I think the performance is identical whether you use Object.create or Class in JS, they both use the prototype under the hood. It's a common point of contention to say that JS already had everything it needed and didn't need classes, because that comes with certain boilerplate and associated patterns that aren't really idiomatic JS, I think that's what he's trying to say here. - The J-Rodge
I just laugh it off these days when it comes to subjects like "use this, don't use that". Just use the tool and method that will solve the problem you work on when you can. In many cases you are working on an existing project that has been designed a certain way and you need to "fit in" so you won't create the frankenstein. Yet we all had the "fun" to work on projects where different part of the application use variety of design patters - oh what fun it is to work on those ones- because particular dev insisted that their design is "bestest" than the other. The only issue I see is the typescript trap that new devs fall into without knowing vanilla JS. I often see online statement like "You don't need to learn JS just learn TS" which puts new devs in an awkward position especially when they finally get their first job and pikachu face all over the office at bespoke source code ;)
13:18 that's why we should have pipe operator in any language (in js I do it through custom function) . btv there is proposal for js about adding pipe operator
The performance callout is strange. If you benchmark class instance methods vs object with bound methods, and functions that accept the object, the class one is actually often faster and lower memory.
As a relatively new frontend dev I have struggled to understand why they are even useful. Ive seen them used for mega menus, buttons and I just don't get it. Someone enlighten me?
Classes are more or less just a familiar syntax for objects with their own “this scope”. Normal struct literal objects in js don’t have their own “this” so it’s difficult to reference “your self”. The way to get a “this scope” in JS is the new keyword, calling a function with new before it creates a “this scope” and applies it to the function being called and if the function doesn’t return a value it returns “this” implicitly or you can explicitly return “this”. Classes work the same way but with a more familiar syntax. You can use classes and constructor functions more or less 1 to 1 but that might change as JS matures further. According to the spec they aren’t currently required to be treated differently by the interpreter. Where are they useful? Classes (scoped objects) have most value you when you have a lot of things that need to keep up with their own state and have methods based on that state. Struct literals can have functions but they can’t easily reference themselves as they don’t have their own scope. They really shine in things like games where you need to co-locate data and self referential functionality.
Imagine you need to describe a medkit in each funtion TakeFromMedkit AddToMedkit ... You could just write a service that accepts the class MedKit MedKitManipulationService with functions accepting the param MedKit Makes it 10 times easier to track what you need to do whern you make changes
Here's my take, since frontend component usually just need to pass or receive "static" attributes. It doesn't really need full encapsulation that class Provide. Example of Class where it is really powerful is in gamedev, since it translate very well, both the structure and the implementation. Enemy, Player on each own has its own move /attack function Do you really need to encapsulate function in frontend? 99% you dont
I prefer to work with the most native object structures in JS. But it needs a lot of boilerplate and comments and readme's to scale and include team members. Honestly, if you work with JavaScript, you need to understand that flexibility is more important than anything else. If you want efficient code, you're using the wrong language. You need not to hold your opinions so strongly. Choose what's the best tool for the situation. For tiny project, i prefer vanilla JavaScript with es6 functionalities, almost exclusively using functions and weakly typing with jsdoc fit the intellisense. If it's web based I'll use the Dom API directly, no jQuery or bootstrap or framework. But most projects are bigger and then I'll use typescript and therefore classes make more sense for many things, but it's not java and I won't force everything into classes. I tend to value readability and clarity in my source code. This article seems to me as written by someone who is rather narrow minded, longing for one way to do everything and strongly opinionated. Possibly someone difficult with whom to work.
Imagine being ECMAScript and a JS engine having years and research on how to simplify and increase performance for prototyping "JavaScript classes" and coming up with JS classes, then a dude comes and is like "nah bro that's slow and stupid trust me bro"
Simpler notation is usually superior. JavaScript is notorious for having so many different ways for doing the same thing: - It's easier to only use === than both === and == - it's easier to use arrow functions than arrow functions, function declarations, and function expressions. - it's easier to use type instead of type and interface - it's easier to use `` than ``, '', and ”” - it's easier to always use curly brackets in block statements, than to sometime omit them and something include them. - it's easier to name variables with camelCase than camelCase, snake_case, and UPPERCASE_SNAKE_CASE. If there are multiple ways to to the same thing, do away with those things that are not absolutely necessary. In most cases, neither classes nor prototypical inheritance are required. However, closures are.
maybe this isn't such a nuanced take but I only use classes when I'm exporting something for use in another script. Or at least if the use case is encapsulated enough, that the state holding function has.
Nah. this is what I consider the most correct use case for classes. It lets you decouple a dependency in a modular manner. Say you have 3 data sets depending on some arbitrary choice. (file type, encryption set, Auth provider, and what have you) Your code can then choose the correct resolver for that particular request going trough your resolver pipeline.. A class gives you easy complete encapsulation and abstraction in those cases where you need it most. Inheritance is just wrong 99.999% of the time unless you have like 50 alternative resolves with only small differences or something. like having a db common set of functions shared by schema types. (GraphQL says hi)
@@MrAnticeI don't think I completely followed what you were trying to convey, could you elaborate on the specific case you have in mind and what the worst off alternative would be?
The best case I know that isn't graphql related is having multiple auth providers. (google, facebook ++) Each of these give you a auth token, that all have different encryption keys and schemes. they all come with their own sdk's from the provider as well in many cases. Your user has a request, and as part of that request they are giving you a bearer token, alongside a header that tells you witch provider it comes from. A typical very bad, but far too common solution is to interact directly with the sdk's, by invoking if cases whenever you need to interact with the provider. in effect, your code has to branch whenever you need to interact with auth related data like access rights etc. something that is a common occurence in business logic. Another common one is to completely resolve all users data in the auth middleware at a substantial hit to performance. I've actually seen implementations that use both of these, and it's pure hell. it breaks really easily during updates of any kind. Using encapsulation and abstraction with classes paired with dependency injection solves the same case with far cleaner code, and you get away with only having to choose dependency in your auth middleware once. The rest of your code is then able to be completely auth provider agnostic. you can even pass a mock auth module for unit testing business logic if you want. (A very good idea btw, especially when there is access controll involved)
Classes are bloatware where you just need to store data in it: objects are much faster than classes. Other than that, classes are sometimes useful of course. For organizing code logic, not for organizing data. Plus, objects are easily composable, in simplest cases it's just enough to { ...ojb1, ...obj2 }, Whereas classes are not as easily composable, instead it assumes you will use inheritance which I guess we all agree is much rarely needed.
11:34, well, if in C 1 write a struct with data and pointers to f()s inside, I believe it'd has the same or better performance than C++'s. But there would be several disadvantages, that I think it would not be worth to be called class: 1) Everything public. This is a disaster for complex projects. It's already a crushing factor, 1 should not use. 2) Pointers could change, pointing to another f() with the same signature. 3) If a class can't hold from public its things, defeats the very propose of it: code security. 4) No inheritance, making things riskier by using composition. 5) No constructor, leaving the programmer to deal with dangerous C initializations. 6) No destructor. Despite nowadays C has a kind of "general destructor" for any kind of variable, it's up to the coder to call it right when the object is created. It's not automatic like a constructor.
From "[Classes are syntactic sugar over prototypes] ... they produce (almost) the same code under the hood" to "2. Performance issues: Because classes implementation"
i might be wrong but I use Js classes only when the previous code uses them and when i need to create an object that does multiple things with the same input, to just declare one and use it mutiple times
Whoever wrote this article is clearly just a React dev and doesn't actually understand JavaScript in general, or how modern engines like V8 work under the hood.
i'm not sure if this is crazy but i've got the idea that in oop, members you can pass as parameters and/or are public should only be derived from interfaces where you can't add any more public members at all, and then as local variables you could have prototype inheritance and extend objects in any way you'd like, but if you pass them to external methods you wouldn't be able to use any of the extensions because the signature of the method specifies an interface and the extensions would not be part of its api. and of course union and intersection types to specify more than one interface at a time, and using existing classes as concrete implementations of interfaces when you inherit them as a way to avoid having to write the same code over again. but never extending a concrete class by itself and never adding globally accessible public members. i don't know if this is just bullshit but i think it'd be nice
You just need to put on a red vest :D yayayayayayayayaya. It is so hilarious that a character like that can make reading an IT article so entertaining :D
I generally don't use classes either but the referenced article makes a poor case. The reason I don't use them is because I find functions a much better primitive. It's lower level, simpler, easier to understand and reason about, and you can construct higher level primitives to create more advanced abstractions. OOP starts at a much higher level primitive and thus doesn't allow you as much control in designing the fundamental architecture / "primitives" of your app.
OOP is very good, but its quite easy to get it wrong and make a mess of spagethi, but well executed i dont think any other paradigm can compete in terms of scalability.
Seeing JavaScript evolve from 1.0, 1.1, and 1.2 using IE4 and Netscape Navigator 4, to quote-unquote stagnating at ES5 for years, to then finally have regular updates kickstarted by ES6, I believe now more than ever it's about using the right tool for the job. That being said, as I commented in another video, "modern JS devs" should be forced to take some time to use only ES5 for a certain period of time (preferably without jQuery) to understand and appreciate not only the limitations of what we had to deal with before the niceties of ES6 and later, but also to understand that there's more than one way to skin a cat, sometimes faster, sometimes cleaner.
I believe people asked for classes in js, just as people argue about using js for frontend and backend. Familiar structures from other languages make seem more relational. Like having a user class in JavaScript which communicates to a class in php called users.. with similar functions .. plus you would have a database table for users .. fields matching functions etc.. I use classes and just objects with functions.. so who knows.
I wholeheartedly agree with this article. JS has Objects but not Classes. Deal with it. It's not so bad. Classes are types and live in a totally different namespace. JS doesn't have that. If you pretend that classes exist then you get weird shit with scope that you don't understand.
Nah, classes and types in general being values is perfectly fine as a language approach, and can lead to some real fun and nice solutions. The problem is that JavaScript, as usual, just did it really badly.
Can someone help me. There was a ThePrimeTime video where he started to rant a little bit and talk about how people don't know terminal tools well enough and they should just learn all their tools inside and out and they can accomplish tasks 10x faster than someone who tries to write it into their app. And then he said something about a terminal tool and he said JC, or JQ? Or something that began with J. Can anyone point me to the primeagen video where he has this rant?
I love static classes - it gives me a useful and encapsulated singleton. I do hate the fact that the methods have no "function" keyword associated with them so they are harder to search for. It might be cool to create a "method" keyword for this purpose, but I think keeping "function" is better. I never use inheritance or OOP so I love the simple use of structures with methods. I also hate inheritance as it is almost as bad as operator overloading. When you invoke a name it should have a single meaning and not potentially many. Programming is poetry and we have good ones and bad poets - all subjectively valued.
I mean... they're cursed because they're objects and you can choose to assign some properties only sometimes... but sometimes they're really useful and can make things like creating a lot of asteroids with random shapes a lot easier, just... asteroids.push(new Asteroid (x,y,direction))
Javascript already had state containers with functions, you just had to know how to make them. JS closures are actually very flexible and powerful, and they promote composition over inheritance.
You are just creating a ghetto class with none of the benefits or optimisations they can do for actual classes. A function which takes state as input and returns an object with functions that operate on that state, is in everything except name a class.
That of private variables in classes is false js classes their just properties starting with a # and they can't be accessed as in you can't access it from other functions. class test { #hiddenVar constructor() { this.#hiddenVar = "Hello world" } log() { console.log(this.#hiddenVar) // will log "Hello world" } } const a = new test() function test2() { console.log(a.#hiddenVar) // Uncaught SyntaxError: Private field '#hiddenVar' must be declared in an enclosing class }
I use classes but I don't usually make them. For most of my applications functional programming is the way to go. maybe if I use canvas to make a silly game I probably use it more. classes are just Blueprints.
2:55 What I'm seeing: This is all solved with `super()`. L24 deep copies all the `Car` properties. L25 sets the current `SportCar`'s constructor to _the function `Car()`_. Now `Sportscar` has no constructor of its own, btw. ... ... When creating a `new Sportscar()` ... L18 gets sent the make, model, turbocharged. L19 Sends the `this`, that being the function `SportsCar()`, to react to the happenings within function `Car()`. That adds the `make` and `model` properties to `SportsCar` yay. Back to L20 now that the `this`, that being the `SportsCar` function we're in, has make and model, let's add the sports car-specific property of `turbocharged`! ... ... Back to the line of scrimmage and you now have a sports car that was created following the steps of creating a regular car and then adding the turbocharge to it! Again, this is what `super()` is for.
Actionscript 3, a typed ECMA dialect from like 2006, had proper classes. To big extent where type script got most of its syntax. Dead just like flash. But AS devs were major factor for TS becoming as relevant as it did
I keep hearing people trying to build an argument for JS classes saying that it "provides better autocomplete" as a major point. IDE type inference is not a language feature or its responsibility. Also, "structs with methods associated with it", which seems to be what this video is most appreciative of from OOP, are simply called "objects" in JS - no need for classes.
Old style classes and moddenr classes are not the same under the hood. Like new classes don't have prototype chains. You make a class and it won't have any prototype. In high level uses, it looks almost the same, but dramatically different even just directly under the surface.
And that matters only in apps that make use of a MASSIVE number of "instances", the footprint will be smaller because prototypes allow to not duplicate a property value for each instance but simply reference it. It causes more operations needed to go up the prototype chain, but imho that's neglectable. I am ignorant tho, about internals or how that's optimized inside engines.
the fact you'll highlight sentences but leave out the first and last character is somehow incredibly satisfying to watch, thank you the highlightagen
aybe it's just me, but I think it's aweso
THIS IS WHY I DO IT. IT FEELS SOOOOO GOOD
@@ThePrimeTimeagen accurate text selection is the final frontier in software accessibility and your blazing the path by showing full-bookending is a fools gamble!
I can’t stop noticing this now
why tho
Javascript: A language where everything's an object but classes aren't real.
lol never thought of it that way but 100% true
@smash3689 really? As a php dev i often think about it.
You just described Smalltalk
All functional first languages are same.
Classes are actually functions.
class Dog {}
typeof Dog === 'function'
JavaScript is the MOST object oriented language. EVERYTHING is an object. It just doesn't have real classes (blueprints for objects), it has prototypes, which are OBJECTS. The Class keyword is just there to make it easier to understand, and it makes perfect sense to work that way. In the end, it's the same.
Javascript's objects are an implementation detail, not a feature.
saying javascript is object oriented because everything is an object s like saying python is a C-oriented programming language because everything is a C library. The average python programmer thinks C is the third letter of the alphabet and doesn't need to know better. That's like saying carpenter is a clay oriented craft just because your neighbor happens to be a carpenter and their workshop is made out of stone.
As an afterthought feature, Javascript's objects are horrendously bad.
The class keyword doesn't help understanding at all, pretty much the opposite. It helps usage, not understanding. It is there for OOP bros who don't even know their own paradigm and couldn't use prototypes to save their life. And I don't blame them, JS is a pretty bad place to learn about prototypes. Every now and then one of em asks a question which boils down to "why does my class not behave like a class", and the answer is simply: "because it's not a class", it's a prototype cosplaying as such. The implementation of classes as an afterthought in JavaScript occurred over several iterations at least twice independently (Typescript).
For example, I can't think of any object oriented language with 4 standard competing ways to do encapsulation, and no that's not a quality.
Use classes when they make your code simpler. Don't when they don't.
I think this goes for all software dev advice. Don't always or never do something just because someone on the internet said so.
But more lines of code and complexity means quality and elegance!
@@danvilela This is the way! The more complex your code is, the more secure your job becomes and the more money you can demand from that company, because their business won't survive without someone understanding that "high quality and elegant" code :D At least until ChatGPT becomes better.
@@danvilelaexaclty. Let me just uhh…
FactoryManagerFactory.CreateFactoryManager(options)
Clean code/solid/Oop have done a lot of damage. People thing you always need a class for everything.
The article is a classic case of rationalization. The author started of with a conclusion and then went searching for arguments to support it, but failed to find any arguments that would support his conclusion or really make any sense at all.
Exactly, using invalids semantics as that. People who complain about OOP really just mean they hate overly abstracted code. Just say that and move on
@@tc2241 no. they're just saying that there are better abstractions out there. the author of the article could've referred to closures as a better alternative to objects and classes, but he's just a boomer stuck on ES5 lol
@@marusdod36855:17
I have a colleague at work trying to create classes for everything and apply design patterns everywhere even for simple logic or single line of code.
It adds a LOT of abstraction for nothing making it harder to debug.
And if you tell him it may be not necessary, he will look down on you for not respecting OOP / Design patterns as taught at school. 😅
Sometimes I wish we would see more KISS in code nowadays.
Tell him to KISS a girl
Your colleague suffers from patternitis maybe he would need to go to doctor
Does your colleague like Java? 😂
i wish i would see more KISS on my lips :(
This is a typical mistake beginners do when first learning OOP. After learning a new design pattern they feel the need to apply it to all of their codebase and completely ignoring any common sense. When it comes to design patters, less is often more.
Javascript objects are not 'just maps' , chromium actually creates c++ structs to improve performance. It's extremely complicated and the compiler does a lot of smart things in the background.
see, that'd be actually useful information, if the article actually was investigating the thing it purported to investigate.
it's just a weird crappy opinion piece.
Do you have any sources or something to read more about it?
This is not part of JS. Chrome does nit compile c++
@@AndriiMuliar You obviously don't know C++ or you'd know what he meant. He said C++ structs. Not code. Learn the difference.
@@DanniDuckstill not part of JS
Prime is literally at a point where his name is the size of an average Java className.
@@nisonatic newing and invoking inline. chadlike
Also public-static-void-main-string-args-agen
The article says that JS Classes are just "Syntactic sugar" . We should use them more then.
Having more readable code with barely any impact to performance is great.
(Like with anything in life, that involves sugar, you should not over do it though.)
Exactly. Too much noise for nothing. And I like classes. I use them in C++ and PHP also. So classes in JS are user friendly for me.
YES. await async is better than promises and those are better than callbacks. try catch is also nice syntactic sugar.
@@sanfords async always return a promise.
Edit: article is from 2020, private attributes were not widely available back then. :)
Private attributes exist in JS, see "Private class features" on MDN. (something the author of the article could've easily looked up before stating something wrong)
Also that "Classes are the same as in ES5" because if you transpile it to ES5 with Babel... was quite dumb :D
TL;DR: Just use JDSL.
At the time the article was posted private fields were not widely supported in browsers. Firefox got the feature over a year later (according to caniuse). I agree that it would have been nice for them to say that it was being worked on, though.
@@Derik. Oh, I should've realised this article is from 2020, thanks for noticing. :)
Then the author was indeed right with that point.
Meanwhile, private variables can always be used in JS via closures.
I don't know why I'm watching this. I've never touched JS.
It's like the Borg... Resistance is futile
JS is everywhere ...
one of us! one of us!
Glad you haven't, my experience with it was i have a feeling of it purposely make me dumber each line i wrote
Your son will be genetically made inside an incubator that runs Javascript so be ready for the future
You programmer tho?
Programmers never stop to amaze me. When a normal person in their work environment doesn't see something useful they won't go online and write an article "Stop using something". But I have seen countless articles or videos of programmers saying "don't use classes, don't use else statements, don't have methods longer than 5 lines of code, don't use a for loop etc etc..." and will give you a few examples that fit their narrative. I can think of dozens of examples where they are useful and also as many where they shouldn't be used.
I saw a “It’s time to say goodbye to Bootstrap” a couple of months ago. I actually read it and as you can guess it was garbage. Just a bunch of “we have tailwind!” And “css is modern” like bootstrap is not constantly taking advantage of new css features
At the end of the day, the message is “just be normal” lol. If you dont like bootstrap, sure, talk about it. But dont pretend like you have arrived to a revolutionary “truth” lol
Don't use else is correct though.
Na this absolutely exists in every industry. You just haven't seen the other industries' blogs yet.
@@brad1785 lol
sure bud@@brad1785
Isn't OOP a concept and not something language specific? C has no concept of clases/objects, but you still can implement OOP with structs, functions and pointers etc
4:55 when you're making tea and the water is hot enough
A month ago, I attended a Node.js Course where I was taught a "thisless" approach in JS and I must say I love it
@oodevr I believe it is nested function definitions whose top-level function returns a bucket object containing the top level function locals and the nested functions. It's cute but a cluster**** in terms of performance. People have dogmatic prejudice against classes.
@@damienlmooreit at least used to be that it was faster than classes, that's why typescript itself is written that way. It currently seems to be slower a lot of the time, but if you unwrap the actual allocations and lookup logic involved, that's not actually necessarily true, they're just missing some fast paths that classes have.
The trade off for not having the semantic clarity of the class syntax is that without using "this", you can much more easily grab a function and call it without using .bind() or .call(), you can have much more natural multiple or private constructors, and without instanceof you can swap it out for tests far more easily.
But I've used both, and you can mix them pretty easily, especially with Typescript interfaces. I mostly just wish Typescript didn't default the this parameter to any.
Maybe is a good approach, i don't know. But it sound like another technique that solves nothing and starts a new religion like clean code and agile.
@oodevr I... can't figure out what you're actually asking? I didn't say that using "this" was slower than scope lookup, I said it at least used to be. As in they've put a lot of work into v8 to make classes less abysmally slow, and now they're mostly just really fast. I also said that there's not really any real reason for scopes to be slower, which I meant to imply that they currently can be slower, but that that could be fixed.
There's not really much in it either way unless you're doing things you shouldn't be doing either way, like allocating a million vectors as objects.
@oodevr just checking: you're aware that JavaScript performance changes, as the implementation has work done on it, right? The v8 blog has lots of examples where using some new feature was something like 50 times (not percent!) slower than some earlier equivalent until they made a fix. Don't pay too much attention to performance numbers without specifically measuring, and don't pay much attention to micro-benchmarks (it's stupidly hard to benchmark JavaScript accurately), and don't keep assumptions about performance around for too long either, as things are fixed.
For example, are you aware that let and const still have something like 10-20% performance impact in real workloads over var, for example? You'd think it wouldn't make any difference, but it absolutely can (sometimes!), and it might not in the future, as I think it's being looked at right now.
The reason I prefer avoiding classes is that it's simpler to think about JavaScript without using "this", not performance. I don't know why you're picking on that point.
"Don't use classes, use something that's less optimized to do the same thing, or just make something objectively more difficult to maintain. Also, classes are less optimized because trust me bro."
Classes actually are much better optimized, especially with the JIT, so that guy is talking out of his ass
Exactly. I’m starting to believe programmer bloggers are just narcissists with an axe to grind
I love the argument "Because react devs told you not to use classes"
This guy seems severely confused what the difference is between a React class component and a JS class. If you don't understand why the react devs moved away from class components, don't write an article mentioning this as an argument against classes. This is so dumb.
yep agree, the moment i saw "Private isnt available" literally null everything he said
Exactly this😂
Modern browsers are able to compile a lot of JS to native behind the scenes on the fly, but that is only really effective if you use classes, otherwise you'd need to hit the same object that did not change over and over again before the JIT bothers.
One reason prototypal OO is more powerful, as far as I understand, is because you can do stuff like building/binding a missing "method" at runtime. In theory there is no limit of complexity in the inheritance scheme you can mimic. It's not necessarily better, it harder to optimise, but it's more powerful.
That being said, I like neither style of OO in JS. For very simple stuff, classes feel like an unnecessary abstraction. For more complex patterns, JS doesn't hide well the prototypes under the hood. And Prototypal syntax in JS is really ugly. And then there is the lack of operator overload, the lack of a type system and the lack of static dispatch, so OO in JS is really just glorified namespace, possibly with some ugly inheritance and poor interfacing. It has no synergy with other feature whatsoever that most other OO language have, baring iteration.
Lua IMO is prototypal OO done right. The approach is extremely minimalist, the syntax is very simple, and you code exactly what you need from OO, nothing more. The downside is you have to code it yourself, but come on, having to code in lua is more of an upside.
JS has always been a powerful lang in all the wrong ways. Prototypical OO doesn't add anything useful to the table and its patterns can be replicated using far better abstractions. Every now and then there's a prototype-related vulnerability in V8 that wouldn't exist had JS been any saner to implement and develop with. JS should've had multiple dispatch like Julia imo. At least that seems to be much truer to the aggressive late-binding early OOP advocated.
Hehe, prototypal OO allows you to implement extension methods, like in C#. It is a little over the hand, and the syntax sucks, but after you put up the scaffold it goes pretty smooth
One major thing overlooked here in this article: with a class definition, IDE’s and LSP’s have a much easier time figuring out how to help you program
It was actually (very) briefly mentioned.
If only that were more true for JavaScript. VS Code and Visual Studio do a decent job but when you start passing class instances as arguments they get totally stupid. Luckily there is a silly but mostly harmless work-around: Add a line of code to your class constructor that checks if the constructor's first parameter is an instance of the class itself and simply return it if so. Then whenever you have a function that wants to accept an argument of that class, reconstruct it at the beginning (e.g. arg1 = new className(arg1)). That's enough to make VS Code and Visual Studio remember the class properties again and give you the correct code completion.
@@stevenleonmusicor just use typescript
just use typescript
god I love those front end dudes they always know everything better then anyone else
JavaScript's OOP style was taken from Self, a language by Sun that took its syntax from Smalltalk, but switched to a new (at the time) prototype based OOP. There was a simple transpiler from Smalltalk to Self, so existing code could be used. NewtonScript for the Apple Newton was based on Self even more so than JavaScript was. JavaScript is more OOP (by the definition of "closer to Smalltalk") than C++ is. Classes actually are different, by the way. Try making an AudioWorklet using prototypes to see what I mean.
Yep, class-oriented OOP isn't the only game in town.
FP multiple dispatch functions may act like class methods (if they are dispatched on first argument alone), but they do not work like OOP methods. The reason is, if you know argument types, you know a method and can resolve it at compile time (even in dynamic language like Julia!). this means that dispatching can be implicitly made static most of the time, and when it is dynamic, it still should match one function with one argument collection.
dispatch functions also do not feel like class methods, they feel like dynamic pattern matching statements, if that makes sense. so your program looks like one giant function, cut into match statement arms.
5:16, yes, recreate it with closures. Factories that return the methods you want that operate on private enclosed values is always a better experience than classes in JavaScript in my opinion.
They used to call it the "module pattern" and it is somewhat similar to commonjs modules
Ah yes, the IIFE closure returning a public interface :-) I used this pattern extensively past and honestly liked it too, but the minute we had support for native classes I dropped it. I just don’t see the downsides of classes - at least not the way I use them.
@@JensRoland I pretty much exclusively write code for a browser and rarely find the need for anything oop-like, so maybe that's why I don't really use them.
Then again I might be stuck in the past a bit too much. Last month I used setTimeout to break a long running fuzzy search algorithm up and prevent it from blocking and make it cancellable. When I was looking at my code after I was done I realized I should have just used a web worker.
@@JensRoland the native classes have no downsides, especially now that you have fully private members. The IIFE closure instead is a bitch and eats a lot of memory
Closures are much slower than classes. JIT compilers optimize classes very well.
While I don't always reach for classes, this "article" just contains a bunch of assumptions with no real explanation behind their reasoning; no digging into JS engine code, like V8 or JavaScriptCore, to see if what they claim holds true at all. To me it's a bunch of baloney until you can actually prove what you're claiming is true.
The only well known fact is that classes are syntatic sugar over prototypes in JS, though. I also highly encourage anyone to read V8 team's article on hidden classes, which are an optimization mechanism for prototypical objects (created through `new` keyword).
For me using “new” and “this” is enough to never use classes. Never!
I try to avoid classes first in JS when functions will do. However, they have their use. Even if its just syntactic sugar.
Me too, I try to use it more like structured data
try to avoid classes -first in JS- when functions will do
People that say OOP (or any other paradigm) is dying or fundamentally bad, or for that matter is the one true way to work, are just outing their lack of experience/ knowledge.
But it's always fun to poke them in public to demonstrate that.
i have seen some gnarly functional components that dance around being stateless when state is actually needed for the application to function. its mainly functional programming pseudointellectuals trying to fit a round peg in a stateless hole
them: don't use classes in JavaScript
me: don't use JavaScript
Isn't this just one of those things where classes aren't the actual problem but people just not knowing how to use classes and following OOP principles sensibly is? Inheritance to me is a great example where I think people shoehorn methods into parent classes that don't belong there as behaviors of the class objects instead of creating a function that takes an object as a parameter, get some data from that object, and then acts on it. Or vice versa where people are afraid to use a class so they define functions that need like 6 parameters do do a thing instead of just writing a class method to a class that already has access to some or all of the data where the behavior would make sense.
JavaScript really said "CLASSES" with the quotation gesture.
Another banger video.
If you want to encapsulate state and methods in JS you can simply put them all in an object. So here he's indirectly referring to using Object.create to wire this type of thing up to a prototype in JS if you want the methods/properties only once in memory - on the base object. Object.create is the newer syntax for using __prototype__, etc.
This would have been an idiomatic way to add to and access the prototype in JS, but it's not used very much since everyone learns Class syntax from other languages and it's more familiar.
It gives performance/memory boost but it's only practical if there are more than 10k instances, you aren't changing the data structure much if at all, and it's a shallow object.
I think the performance is identical whether you use Object.create or Class in JS, they both use the prototype under the hood. It's a common point of contention to say that JS already had everything it needed and didn't need classes, because that comes with certain boilerplate and associated patterns that aren't really idiomatic JS, I think that's what he's trying to say here. - The J-Rodge
That was a shitastic article. I love how the author provided plenty of examples showing how prototypal delegation is better than ES6 class syntax!
what does shitastic even mean, is that a good or a bad thing?
@@FlanPoirotprobably "so shit it's funny and thus fun to read"
I just laugh it off these days when it comes to subjects like "use this, don't use that". Just use the tool and method that will solve the problem you work on when you can. In many cases you are working on an existing project that has been designed a certain way and you need to "fit in" so you won't create the frankenstein. Yet we all had the "fun" to work on projects where different part of the application use variety of design patters - oh what fun it is to work on those ones- because particular dev insisted that their design is "bestest" than the other.
The only issue I see is the typescript trap that new devs fall into without knowing vanilla JS. I often see online statement like "You don't need to learn JS just learn TS" which puts new devs in an awkward position especially when they finally get their first job and pikachu face all over the office at bespoke source code ;)
For front-end true. But is feasible in Node.JS to not use classes?
When im in a writing bad, biased, childish articles competition and my opponent is a JS Brain programmer
OMG thanks for being a person that knows how to distinguish good programming practices like encapsulation from OOP specific implementations!
And yet, encapsulation is the sole reason OOP sucks. At a fine-grained level it just doesn't work
13:18 that's why we should have pipe operator in any language (in js I do it through custom function) . btv there is proposal for js about adding pipe operator
Pipe would be so awesome to have. It's one of those things from elixir I always miss in js. that and proper pattern matching. switch is cumbersome.
The performance callout is strange.
If you benchmark class instance methods vs object with bound methods, and functions that accept the object, the class one is actually often faster and lower memory.
As a relatively new frontend dev I have struggled to understand why they are even useful.
Ive seen them used for mega menus, buttons and I just don't get it.
Someone enlighten me?
Because you’re working on frontend
Classes are more or less just a familiar syntax for objects with their own “this scope”. Normal struct literal objects in js don’t have their own “this” so it’s difficult to reference “your self”. The way to get a “this scope” in JS is the new keyword, calling a function with new before it creates a “this scope” and applies it to the function being called and if the function doesn’t return a value it returns “this” implicitly or you can explicitly return “this”. Classes work the same way but with a more familiar syntax. You can use classes and constructor functions more or less 1 to 1 but that might change as JS matures further. According to the spec they aren’t currently required to be treated differently by the interpreter.
Where are they useful? Classes (scoped objects) have most value you when you have a lot of things that need to keep up with their own state and have methods based on that state. Struct literals can have functions but they can’t easily reference themselves as they don’t have their own scope. They really shine in things like games where you need to co-locate data and self referential functionality.
They are really good for custom elements
Imagine you need to describe a medkit in each funtion
TakeFromMedkit
AddToMedkit
...
You could just write a service that accepts the class MedKit
MedKitManipulationService with functions accepting the param MedKit
Makes it 10 times easier to track what you need to do whern you make changes
Here's my take, since frontend component usually just need to pass or receive "static" attributes. It doesn't really need full encapsulation that class Provide.
Example of Class where it is really powerful is in gamedev, since it translate very well, both the structure and the implementation. Enemy, Player on each own has its own move /attack function
Do you really need to encapsulate function in frontend? 99% you dont
I prefer to work with the most native object structures in JS.
But it needs a lot of boilerplate and comments and readme's to scale and include team members.
Honestly, if you work with JavaScript, you need to understand that flexibility is more important than anything else. If you want efficient code, you're using the wrong language.
You need not to hold your opinions so strongly.
Choose what's the best tool for the situation.
For tiny project, i prefer vanilla JavaScript with es6 functionalities, almost exclusively using functions and weakly typing with jsdoc fit the intellisense. If it's web based I'll use the Dom API directly, no jQuery or bootstrap or framework.
But most projects are bigger and then I'll use typescript and therefore classes make more sense for many things, but it's not java and I won't force everything into classes. I tend to value readability and clarity in my source code.
This article seems to me as written by someone who is rather narrow minded, longing for one way to do everything and strongly opinionated.
Possibly someone difficult with whom to work.
Imagine being ECMAScript and a JS engine having years and research on how to simplify and increase performance for prototyping "JavaScript classes" and coming up with JS classes, then a dude comes and is like "nah bro that's slow and stupid trust me bro"
Simpler notation is usually superior. JavaScript is notorious for having so many different ways for doing the same thing:
- It's easier to only use === than both === and ==
- it's easier to use arrow functions than arrow functions, function declarations, and function expressions.
- it's easier to use type instead of type and interface
- it's easier to use `` than ``, '', and ””
- it's easier to always use curly brackets in block statements, than to sometime omit them and something include them.
- it's easier to name variables with camelCase than camelCase, snake_case, and UPPERCASE_SNAKE_CASE.
If there are multiple ways to to the same thing, do away with those things that are not absolutely necessary. In most cases, neither classes nor prototypical inheritance are required. However, closures are.
Using classes isn't bad, but most things don't benefit in any way from it, and it introduces a lot of extra complexity where it shouldn't be.
JS was inspired by self which is described as, "an object-oriented programming language based on the concept of prototypes." 🙃
maybe this isn't such a nuanced take but I only use classes when I'm exporting something for use in another script. Or at least if the use case is encapsulated enough, that the state holding function has.
Nah. this is what I consider the most correct use case for classes. It lets you decouple a dependency in a modular manner. Say you have 3 data sets depending on some arbitrary choice. (file type, encryption set, Auth provider, and what have you)
Your code can then choose the correct resolver for that particular request going trough your resolver pipeline.. A class gives you easy complete encapsulation and abstraction in those cases where you need it most.
Inheritance is just wrong 99.999% of the time unless you have like 50 alternative resolves with only small differences or something. like having a db common set of functions shared by schema types. (GraphQL says hi)
@@MrAnticeI don't think I completely followed what you were trying to convey, could you elaborate on the specific case you have in mind and what the worst off alternative would be?
The best case I know that isn't graphql related is having multiple auth providers. (google, facebook ++)
Each of these give you a auth token, that all have different encryption keys and schemes. they all come with their own sdk's from the provider as well in many cases.
Your user has a request, and as part of that request they are giving you a bearer token, alongside a header that tells you witch provider it comes from.
A typical very bad, but far too common solution is to interact directly with the sdk's, by invoking if cases whenever you need to interact with the provider. in effect, your code has to branch whenever you need to interact with auth related data like access rights etc. something that is a common occurence in business logic.
Another common one is to completely resolve all users data in the auth middleware at a substantial hit to performance.
I've actually seen implementations that use both of these, and it's pure hell. it breaks really easily during updates of any kind.
Using encapsulation and abstraction with classes paired with dependency injection solves the same case with far cleaner code, and you get away with only having to choose dependency in your auth middleware once. The rest of your code is then able to be completely auth provider agnostic. you can even pass a mock auth module for unit testing business logic if you want. (A very good idea btw, especially when there is access controll involved)
Classes are bloatware where you just need to store data in it: objects are much faster than classes.
Other than that, classes are sometimes useful of course. For organizing code logic, not for organizing data.
Plus, objects are easily composable, in simplest cases it's just enough to { ...ojb1, ...obj2 },
Whereas classes are not as easily composable, instead it assumes you will use inheritance which I guess we all agree is much rarely needed.
STOP using classes in a language that interacts with web APIs like literal Document OBJECT Model
i find this types of videos so educational, thanks daddy prime. ❤
Isn't like everything just syntactic sugar for machine code?
11:34, well, if in C 1 write a struct with data and pointers to f()s inside, I believe it'd has the same or better performance than C++'s. But there would be several disadvantages, that I think it would not be worth to be called class:
1) Everything public. This is a disaster for complex projects. It's already a crushing factor, 1 should not use.
2) Pointers could change, pointing to another f() with the same signature.
3) If a class can't hold from public its things, defeats the very propose of it: code security.
4) No inheritance, making things riskier by using composition.
5) No constructor, leaving the programmer to deal with dangerous C initializations.
6) No destructor. Despite nowadays C has a kind of "general destructor" for any kind of variable, it's up to the coder to call it right when the object is created. It's not automatic like a constructor.
In C you can easily make things private by not exposing it in the header file.
From "[Classes are syntactic sugar over prototypes] ... they produce (almost) the same code under the hood"
to "2. Performance issues: Because classes implementation"
Love how someone in his chat brought up LSP. Made me feel good, cause i was thinking the same thing
i might be wrong but I use Js classes only when the previous code uses them and when i need to create an object that does multiple things with the same input, to just declare one and use it mutiple times
Prime, composition works just as well for event emitters, no need to use inheritance for that
Yup...event dispatch libraries that leverage composition - like MiniSignals - are a God send.
I read this somewhere - In programming, it's all about trade-offs; every gain comes with a loss :)
Is there vim for manipulating DOM? Like for note taking in html. Yank and paste styles.
Whoever wrote this article is clearly just a React dev and doesn't actually understand JavaScript in general, or how modern engines like V8 work under the hood.
Do you
i'm not sure if this is crazy but i've got the idea that in oop, members you can pass as parameters and/or are public should only be derived from interfaces where you can't add any more public members at all, and then as local variables you could have prototype inheritance and extend objects in any way you'd like, but if you pass them to external methods you wouldn't be able to use any of the extensions because the signature of the method specifies an interface and the extensions would not be part of its api. and of course union and intersection types to specify more than one interface at a time, and using existing classes as concrete implementations of interfaces when you inherit them as a way to avoid having to write the same code over again. but never extending a concrete class by itself and never adding globally accessible public members. i don't know if this is just bullshit but i think it'd be nice
That guys whole rant is him not understanding that you can have oop w/o classes
You just need to put on a red vest :D yayayayayayayayaya. It is so hilarious that a character like that can make reading an IT article so entertaining :D
I generally don't use classes either but the referenced article makes a poor case. The reason I don't use them is because I find functions a much better primitive. It's lower level, simpler, easier to understand and reason about, and you can construct higher level primitives to create more advanced abstractions. OOP starts at a much higher level primitive and thus doesn't allow you as much control in designing the fundamental architecture / "primitives" of your app.
Is your shell transparent or is that a wallpaper for your shell?
Please anyone, how do I do this line number style in emacs? 3:01
5:40 Can someone, please, point me to which article Prime's referring to?
I use class to encapsulate related method. so I get jsdoc and vscode lens stuff. I think other than that, it's pretty much make things more complex
Thank you for another classy video!
OOP is very good, but its quite easy to get it wrong and make a mess of spagethi, but well executed i dont think any other paradigm can compete in terms of scalability.
Seeing JavaScript evolve from 1.0, 1.1, and 1.2 using IE4 and Netscape Navigator 4, to quote-unquote stagnating at ES5 for years, to then finally have regular updates kickstarted by ES6, I believe now more than ever it's about using the right tool for the job. That being said, as I commented in another video, "modern JS devs" should be forced to take some time to use only ES5 for a certain period of time (preferably without jQuery) to understand and appreciate not only the limitations of what we had to deal with before the niceties of ES6 and later, but also to understand that there's more than one way to skin a cat, sometimes faster, sometimes cleaner.
I'm so happy I found this channel
I heard reverse story not a function is an object but objects underneath are fuctions...
I believe people asked for classes in js, just as people argue about using js for frontend and backend. Familiar structures from other languages make seem more relational. Like having a user class in JavaScript which communicates to a class in php called users.. with similar functions .. plus you would have a database table for users .. fields matching functions etc..
I use classes and just objects with functions.. so who knows.
I wholeheartedly agree with this article.
JS has Objects but not Classes. Deal with it. It's not so bad.
Classes are types and live in a totally different namespace.
JS doesn't have that. If you pretend that classes exist then you get weird shit with scope that you don't understand.
Nah, classes and types in general being values is perfectly fine as a language approach, and can lead to some real fun and nice solutions. The problem is that JavaScript, as usual, just did it really badly.
A JavaScript class is whatever JavaScript decrees is a class.
"Is the arbiter"
Hmmm thats my new favourite word
As a person who doesn’t even know what classes are in JavaScript, I completely agree
Can someone help me. There was a ThePrimeTime video where he started to rant a little bit and talk about how people don't know terminal tools well enough and they should just learn all their tools inside and out and they can accomplish tasks 10x faster than someone who tries to write it into their app. And then he said something about a terminal tool and he said JC, or JQ? Or something that began with J. Can anyone point me to the primeagen video where he has this rant?
you sure did dirty shedding light again in this guy's 2020 article, classes are ok, just avoid inheritance
10:30 - as much as I try to think about perf/memory(thanks to you
I love static classes - it gives me a useful and encapsulated singleton. I do hate the fact that the methods have no "function" keyword associated with them so they are harder to search for. It might be cool to create a "method" keyword for this purpose, but I think keeping "function" is better. I never use inheritance or OOP so I love the simple use of structures with methods. I also hate inheritance as it is almost as bad as operator overloading. When you invoke a name it should have a single meaning and not potentially many.
Programming is poetry and we have good ones and bad poets - all subjectively valued.
I mean... they're cursed because they're objects and you can choose to assign some properties only sometimes... but sometimes they're really useful and can make things like creating a lot of asteroids with random shapes a lot easier, just... asteroids.push(new Asteroid (x,y,direction))
I realize that this is probably one of the only cases where OOB is actually useful at all 😅
Javascript already had state containers with functions, you just had to know how to make them. JS closures are actually very flexible and powerful, and they promote composition over inheritance.
You are just creating a ghetto class with none of the benefits or optimisations they can do for actual classes.
A function which takes state as input and returns an object with functions that operate on that state, is in everything except name a class.
like it or not, prototype based OOP is still OOP
The use of both JS and JavaScript in the same article drove me crazy
you should have bigger problems than that in life my boy
Time to read Eloquent Javascript again
Private variables are absolutely a thing in JavaScript. Lead the class property with a sharp (#) and it will not be accessible outside the class.
they were only added in ECMAScript 2022 so are relatively new afaict
That of private variables in classes is false js classes their just properties starting with a # and they can't be accessed as in you can't access it from other functions.
class test {
#hiddenVar
constructor() {
this.#hiddenVar = "Hello world"
}
log() {
console.log(this.#hiddenVar) // will log "Hello world"
}
}
const a = new test()
function test2() {
console.log(a.#hiddenVar) // Uncaught SyntaxError: Private field '#hiddenVar' must be declared in an enclosing class
}
love the concept of react brain damage. I feel it myself
I use classes but I don't usually make them. For most of my applications functional programming is the way to go. maybe if I use canvas to make a silly game I probably use it more. classes are just Blueprints.
A functional component with props getters and setters... is a class ;)
2:55 What I'm seeing: This is all solved with `super()`.
L24 deep copies all the `Car` properties.
L25 sets the current `SportCar`'s constructor to _the function `Car()`_. Now `Sportscar` has no constructor of its own, btw.
... ... When creating a `new Sportscar()` ...
L18 gets sent the make, model, turbocharged.
L19 Sends the `this`, that being the function `SportsCar()`, to react to the happenings within function `Car()`. That adds the `make` and `model` properties to `SportsCar` yay.
Back to L20 now that the `this`, that being the `SportsCar` function we're in, has make and model, let's add the sports car-specific property of `turbocharged`!
... ... Back to the line of scrimmage and you now have a sports car that was created following the steps of creating a regular car and then adding the turbocharge to it!
Again, this is what `super()` is for.
why does he say there's no private fields
what does # do, then
2:40 - Is this a @edbassmaster reference? lol
Private variables are absolutely a thing. You need to prefix them with a # and that’s it. And that’s in JavaScript itself, not typescript.
Actionscript 3, a typed ECMA dialect from like 2006, had proper classes. To big extent where type script got most of its syntax. Dead just like flash. But AS devs were major factor for TS becoming as relevant as it did
its all depend classes can save you from writing more of the same code.
I use classes when im building a game also. I think its all depends.
I keep hearing people trying to build an argument for JS classes saying that it "provides better autocomplete" as a major point. IDE type inference is not a language feature or its responsibility.
Also, "structs with methods associated with it", which seems to be what this video is most appreciative of from OOP, are simply called "objects" in JS - no need for classes.
thanks. I will continue use classes 😊
The only thing I don't like classes is because they are not minifiable and for most web apps this matter to make a really fast startup app.
you should learn how LZ77 works
Old style classes and moddenr classes are not the same under the hood.
Like new classes don't have prototype chains. You make a class and it won't have any prototype.
In high level uses, it looks almost the same, but dramatically different even just directly under the surface.
And that matters only in apps that make use of a MASSIVE number of "instances", the footprint will be smaller because prototypes allow to not duplicate a property value for each instance but simply reference it.
It causes more operations needed to go up the prototype chain, but imho that's neglectable.
I am ignorant tho, about internals or how that's optimized inside engines.
4:50... Am I the only one who noticed that F5 to B5 falsetto?!