4 ms·
Inheritance in the OOP sense can be simply implemented in most languages without OOP. In Javascript: var o1 = { a: 1, b: 2, c: 3 } var o2 = { x: 1, y: 2, z
by tarkin2 5y ago
Inheritance in the OOP sense can be simply implemented in most languages without OOP. In Javascript:
var o1 = { a: 1, b: 2, c: 3 }
var o2 = { x: 1, y: 2, z: 3 }
o1 = Object.assign(o1, o2)
o1.z // 3
o1 has now inherited o2. I don't see much difference between this and classic untyped OOP.
Edit: copying functions over, not values, is what I’m getting at. Values used for simplicity of example
- tsimionescu 5y agoWhile it's true that it's easy to implement inheritance in dynamic languages, it's not quite this easy. The most important feature of inheritance is the function override support / virtual dispatch, so that o1.foo() and o2.foo() can do different things, but o2.foo() can also access o1.foo() (by using something like super.foo() in Java or BaseClass::foo() in C++). Ideally this would also be optimized so that each object doesn't have to carry a function pointer for each member function (this is why virtual function tables are generally used).
- tarkin2 5y agoOverride support, no? function f() { function g() { return 1 } return { g } } function f1(f) { function g() { return f.g() + 1 } return { g } } f1(f())
- tsimionescu 5y agoSure, but that's a whole bunch more boilerplate than just .assign(), which was my point (it's easy, but not quite as easy as just calling assign). Especially since f needs to be written a certain way to be overridable, while in the previous example o1 was just an ordinary object. Edit: Not to mention that storing function pointers with each object is a huge waste of memory, versus storing one class pointer in each object, and having that class object store function pointers and parent class pointers. That way, you guarantee that each function pointer is stored exactly once, and each object has a single sizeof(pointer) of overhead (and even this can be improved with more complex implementations).
- trgn 5y agoThis work-around copies the values (in your examples), or the references (if the props are functions or objects), which is just wasted cycles and memory bloat. It's harder for runtimes to optimize, because with that mixin `o1` changes its shape. It's harders for IDEs to infer the type of `o1`, which will hurt navigating and searching through your codebase with confidence. Implementing OOP in JS with hacks like this is worse, in pretty much all ways, apart from the intellectual kick many devs get of avoiding OOP at all cost, as opposed to just using built-in language features.
- CRConrad 5y agoSeems to me to be very different from the OO concept of inheritance: You're copying values between variables, instances of a type. The OO idea is about the type definition; it affects all instances of a type without any per-instance boilerplate code at all.