DEV Community

Discussion on: OOPS in JS - Ultimate

Collapse
 
efpage profile image
Eckehard

How do you get this in Javascript?

Key Points of Method Overriding:

  1. Same Parameters: The method in the child class must have the same parameter list as the parent class method.

Even declaring public methods "by convention" seems to be a strange concept. Some of this concepts in OO-languages are used to enable better checks by the compiler. But in JS nobody will protect you from doing thing wrong...

Collapse
 
codexam profile image
Subham

JavaScript does indeed handle things differently from stricter OOPs languages. Method overriding in JavaScript works through the prototype chain/inheritance.

Note: When you create a class (or constructor function) in JavaScript, it sets up a prototype chain. When a child class extends a parent class, it links their prototypes. When you call a method on an object, JavaScript first looks for that method on the object itself. If it doesn't find it, it looks up the prototype chain.

While it doesn't enforce the same rigid rules, we can still apply similar principles. In JS, we override methods simply by defining them in the child class with the same name. The beauty (and potential danger) is that JS doesn't fuss about matching parameters or access levels, it's all on us to keep things consistent.

Here's what we can do (but probably shouldn't):

class Parent {
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

class Child extends Parent {
  greet(name, age) {  // Different parameters, JS doesn't complain
    console.log(`Hi ${name}, you're ${age} years old!`);
  }
}
Enter fullscreen mode Exit fullscreen mode

And here's a better approach we should follow:

class Parent {
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

class Child extends Parent {
  greet(name) {  // Same parameters as parent
    super.greet(name);  // Call parent method
    console.log("How are you doing?");
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
efpage profile image
Eckehard

In my experience, OOP rules serve mainly to protect a programmer's against his worst enemy: Himselve! Regardless how good your style is, if you revisit a code month later - or are lucky to even reuse a larger portion of another project that was battle tested - you are happy if your code contains some barriers against unwanted mutation.

The worst things are often done with a good intention!

Maybe I´m wrong, but even the prototype chain is pretty careless with respect to types. I´m not aware that even the number of parameters matters. As long as a childs method was found in the parent, it is overwritten, regardless how it was defined.