1

I've been digging into React's codebase and I discovered that when you write class App extends React.Component, you are actually extending an object created by the following function:

function Component (props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = {};
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue ;
}

Component.prototype.isReactComponent = {};

Component.prototype.setState = function(partialState, callback) {
  this.updater.enqueueSetState(this, partialState, callback, 'setState')
}

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
}

What is the advantage of creating classes this way as opposed to just writing an ES6 class?

  • 3
    The advantage is that this code runs in environments that don't support `class` syntax without having to preprocess the code. It produces the same result as using `class`. – Felix Kling Mar 19 '19 at 20:21
  • Not sure why they aren't using Babel to transpile it down ... – Jonas Wilms Mar 19 '19 at 20:26
  • Maybe so that it supports being extended in ES5 style? – Bergi Mar 19 '19 at 20:33
  • An ES6 class it's only syntactic sugar for the developer at the end a `class` will be converted to a function – OsDev Mar 19 '19 at 20:59
  • @OsDev No, it won't be converted to different syntax. And classes are [not only syntactic sugar](https://stackoverflow.com/a/48036928/1048572). – Bergi Mar 19 '19 at 21:06
  • @Bergi Actually, in the end, it's an abstraction of prototypal inheritance, so syntactic sugar for people that come from the OOP world – OsDev Mar 19 '19 at 22:09

1 Answers1

1

https://caniuse.com/#search=es6%20class

This has to do with browser compatibility. Ensuring that the code can run where the class sytax is not supported without having to transpile with something like Babel.

Mark
  • 1,610
  • 1
  • 14
  • 27