re: Write a function that shows off something unique or interesting about the language you're using VIEW POST


Lots of languages support that, including most obviously Javascript.


Interesting. Is that possible via class definitions (class syntax I mean) or only via the prototype syntax?

Yeah - sorry, meant to demonstrate that you can attach a function via prototype to a class defined with class syntax.

Right - something like this is fine:

class Foo {
  method1() {
    console.log("Method one")

Foo.prototype.method2 = function(){ console.log("Method too") }

Thanks to the batshit insane way that this works, it's a full-blown method.

This capability isn't unusual. In Python, you can also add methods to instances, but you need to ensure you handle self:

class Foo:
  def __init__(self):
    # Some code

f = Foo()

dir(f) ## Returns ['__doc__', '__init__', '__module__']

Foo.method = lambda self, x: x

dir(f) ## Now includes our new method

f.method(22) ## Returns 22.

Languages such as C++ and Java, on the other hand, have immutable types (and in the former, types aren't themselves even a type).

code of conduct - report abuse