Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between extending Object vs not extending at all in javascript?

I found out that I can extend Object like this:

class MyObject extends Object {}

Is there any difference with this and not extending at all, like this:

class MyObject {}

The reason I ask this is because I have the following mixin:

const MapMixin = (Base = Object) => class extends Base {
  static from(array) {
    return new this(Object.assign(...array.map(([key, value]) => ({[key]: value}))));
  }

  map(...args) {
    return this.constructor.from(this.entries().map(...args));
  }

  entries() {
    return Object.entries(this);
  }
};

This mixin could be used like this:

class MyObject extends MapMixin(MyBaseClass) {}

But if there is no base class, I now have specified that it then extends Object as default:

class MyObject extends MapMixin() {}

So I'm wondering, if this practically works the same as not extending anything at all.

like image 955
Kasper Avatar asked Oct 17 '17 08:10

Kasper


Video Answer


1 Answers

I don't know if it's clear from the other answers here, but the difference is in the static inheritance.

Prior to the class keyword, inheritance in JavaScript has been very focused on instance inheritance. No one (that I've seen) cared to go through the trouble of having one class/constructor inherit static members from the super class/constructor. Not to mention the only way to do this was through the non-standard __proto__ property.

So when we look at a class extending another class today, we think about how inheritance works between instances of that class. For instances, extending Object, or nothing at all, is the same because instances will inherently inherit from Object as a base.

class A {}
class B extends Object {}

let a = new A()
let b = new B()

// a.__proto__.__proto__ === b.__proto__.__proto__ === Object.prototype 

But it may not be clear, or well understood that the extends keyword is doing more than just setting up inheritance for instances. It also sets up inheritance between the class constructors. So for B above, the use of extends also means a Object.setPrototypeOf(B, Object) getting called in the background for B. So, for example:

class A {} // A constructor inherits nothing (is a basic Function type)
class B extends Object {} // B inherits from Object

// A.setPrototypeOf === undefined
// B.setPrototypeOf === Object.setPrototypeOf

B, extending Object, inherits all the static methods from Object, whereas A not extending anything, doesn't.

The difference is between B.prototype (or B.prototype.__proto__) - what instances inherit from, and B.__proto__ - what the class constructor inherits from. Extending Object or not does not affect the prototype or what the instances inherit from, but it does affect the class's __proto__, or static inheritance.

like image 108
senocular Avatar answered Nov 15 '22 04:11

senocular