Hacker News new | past | comments | ask | show | jobs | submit login

> Python lets you do _far_ more shenanigans that Javascript does

Does JavaScript let you do this monstrosity of terrible code?

    Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> class Dog(object):
    ...     def speak(self):
    ...             print("bark!")
    ... 
    >>> class Cat(object):
    ...     def speak(self):
    ...             print("meow!")
    ...
    >>> animal = Dog()
    >>> animal.speak()
    bark!
    >>> animal.__class__ = Cat
    >>> animal.speak()
    meow!
    >>>



A lot of people have responded "yes", but no one's taught you how yet, so here's some example code that you can paste into your browser's Devtools or Node's REPL:

    class Dog {
      speak() {
        console.log("bark!");
      }
    }
    class Cat {
      speak() {
        console.log("meow!");
      }
    }
    animal = new Dog();
    animal.speak();
    Object.setPrototypeOf(animal, Cat.prototype);
    animal.speak();
This will produce:

    bark!
    meow!


Yes, you absolutely can. In fact, this was part of my ES5 Date constructor polyfill.


You can replace an object's prototype in JS, wouldn't that do the same?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: