Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking up an ES6 class into multiple files [duplicate]

With a JavaScript 'class' (not really a class, I know), it's possible to break up a big definition by putting methods in separate files, like this:

var Foo = function () {
  console.log('initializing foo');
};

Foo.prototype.render = require('./render');

But with ES6 classes, it looks like the syntax rules out this approach – it seems the methods always have to be written as function literals inside the class block.

I tried this in the 6to5 REPL:

class Foo {
  constructor() {
    console.log('initializing foo');
  }

  require('./render');
}

...but it errors.

As an example, CoffeeScript's class syntax allows me to do this:

class Foo
  constructor: ->
    console.log 'initializing foo'

  render: require './render'

Is there really no way to do this with ES6 classes?

like image 292
callum Avatar asked Jan 16 '15 13:01

callum


1 Answers

Classes are just syntactic sugar. So you can do

class Foo {
  constructor() {
    console.log('initializing foo');
  }
}

Foo.prototype.render = require('./render');

Or you could create a getter:

class Foo {
  constructor() {
    console.log('initializing foo');
  }

  get render() {
    return require('./render');
  }
}
like image 193
Felix Kling Avatar answered Sep 28 '22 11:09

Felix Kling