JavaScript Classes: Not What You Think

JavaScript Doesn't Have Classes!   Yes, that's correct. Anyone who started using JavaScript after 2015 will be very confused by this statement.   "But I saw the class syntax in the intro course I took when I started programming!"   Which would also be accurate.   JavaScript has a syntax for classes, but under the hood, no class in the Java/C++ sense is being declared. Don't believe me? Go run this in your browser console: class Test { constructor() { this.prop = "test"; } } console.log(typeof Test); Yes, it's a function. JavaScript classes essentially do two things: create a constructor function that works with the "new" keyword, and set up a prototype object (more on that another time). "Okay, but it's still basically a class." No, not really. Try this code (hopefully you tried the one above first): let x = new Test(); Now you have a Test object with one property, "prop". Now do this: x.newprop = "newprop"; This runs. In most other languages, this would be grounds for the compiler to crash your IDE out of pure spite. It runs in JavaScript because the class was never acting as a blueprint, it was just a special constructor function all along. If you've always been confused by the __proto__ property when checking Javascript objects and too scared to ask what it is, well it's part of the same conspiracy, I will be writing about it in my next post   #javascript #webdevelopment #programming

  • graphical user interface, text, application

function myClassA() { this.myProp = 123; } const instance = new myClassA(); function myClassB() { myClassA.call(this); this.nextProp = 111; } Same as class myClassB extends myClassA { ... } The Difference is, class methods go in prototype, but you can use ES5 prototype design pattern.

Like
Reply

To view or add a comment, sign in

Explore content categories