1

I discovered today that this seems to be legal javascript:

class foo {
   a() { console.log( 'a' ); }
   b() { console.log( 'b' ); }
   a() { console.log( 'a2' ); }
}

( new foo() ).a(); // shows a2

The a() function is listed twice, but javascript just ignores the first one. Why is this legal? What is a meaningful use case for this "feature"?

Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
  • 1
    I think the actual answer may be that "classes" in JavaScript can be created dynamically, so making this construction legal gives the program the power to decide at runtime, based on whatever new information it may have, which version of the method to use. – Cat Jan 06 '22 at 19:16
  • Fine, [here's](https://stackoverflow.com/q/64852311/476) an actual 100% duplicate, which was closed in favour of [this](https://stackoverflow.com/q/30617139/476). – deceze Jan 06 '22 at 20:03
  • @deceze Surely you can't mark a question as a duplicate if the original question has been deleted? That said, the [reason it was closed](https://stackoverflow.com/questions/30617139/whats-the-purpose-of-allowing-duplicate-property-names) seems valid. Thanks – Graeme Perrow Jan 06 '22 at 20:09

0 Answers0