DEV Community

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

 
dwd profile image
Dave Cridland

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).