Sobes.tech
Middle

What is the difference between classes in JavaScript and classes in other programming languages?

sobes.tech AI

Answer from AI

In JavaScript, classes are syntactic sugar over prototypal inheritance. In other languages, such as Java or C++, classes are a fundamental part of the type system and are based on classical inheritance, where objects are instances of classes.

Main differences:

Feature JavaScript (Classes) Classical Languages (Classes)
Inheritance Model Prototypal (delegation through the prototype chain) Classical (inheritance of properties and methods from a parent class)
Object Creation Via new or factory functions (emulation) Via new based on class definition
Properties Can be added dynamically to an instance Defined in the class, instances have them by default
Data "Protection" No strict privacy at the syntax level Support for access modifiers (private, protected, public)
"Classes" Essentially constructor functions with a prototype Separate language entities

In JS, classes provide a more familiar syntax for working with objects and inheritance, but under the hood, they still operate on prototypes. For example, when trying to access a property on an instance, the JS engine first looks at the instance itself, then its prototype, then the prototype of the prototype, and so on up the chain.

// Example in JavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const myDog = new Dog('Buddy');
myDog.speak(); // Prototype inheritance: the speak method is found in the Dog prototype, then in the Animal prototype

// Adding a property dynamically
myDog.age = 3;
console.log(myDog.age);
// Example in Java (for comparison)
class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " makes a sound.");
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    @Override
    public void speak() {
        System.out.println(name + " barks.");
    }
}

// Creating an instance
Dog myDog = new Dog("Buddy");
myDog.speak(); // Classical inheritance: the speak method is inherited from Animal and overridden in Dog

// Cannot add properties dynamically unless defined in the class
// myDog.age = 3; // Compilation error

Unlike many classical languages where classes define a rigid object structure, in JS, class instances are more "flexible" and allow adding or removing properties and methods dynamically, although this approach is often considered an anti-pattern. Private fields in JS were introduced later and use the # syntax, which differs from the keywords private, protected, and public.