10

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?

callum
  • 34,206
  • 35
  • 106
  • 163

2 Answers2

13

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');
  }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

What about this?

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

  render() { 
    require('./render'); 
  }
}
mutil
  • 3,205
  • 1
  • 27
  • 34