Adviov
Adviov

Reputation: 480

Class methods undefined with Node + ES6 + Babel

I'm trying to run an express app in ES6. I'm using the following workflow:

  1. Transpile ES6 to ES5 using the following gulp task (with "es2015" and "stage-0" presets in .babelrc):

    import gulp from 'gulp';
    import gulpBabel from 'gulp-babel';
    import sourcemaps from 'gulp-sourcemaps';
    
    gulp.task('babel', () => {
        gulp.src([
                'someClass.js',
                'app.js'
            ], {base: './', dot: false})
            .pipe(sourcemaps.init())
            .pipe(gulpBabel())
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./dist'));
    });
    

    Which seems to be working fine.

  2. Run node dist/app.js.

  3. The following code is in someClass.js:

    export default class SomeClass {
    
        someMethod() {
            return 1 + 1;
        }
    }
    
  4. Finally, the following code is in app.js:

    import SomeClass from './someClass';
    
    //express config
    
    console.log(SomeClass);
    console.log(SomeClass.someMethod);
    

Which logs:

[Function: SomeClass]
undefined

Here is the relevant transpiled code:

dist/app.js

var _someClass = require('./someClass');

var _someClass2 = _interopRequireDefault(_someClass);

console.log(_someClass2.default);
console.log(_someClass2.default.someMethod);

dist/someClass.js

var SomeClass = function () {
    function SomeClass() {
        _classCallCheck(this, SomeClass);
    }

    _createClass(SomeClass, [{
        key: "someMethod",
        value: function someMethod() {
            return 1 + 1;
        }
    }]);

    return SomeClass;
}();

exports.default = SomeClass;

Why is someMethod undefined?

Upvotes: 3

Views: 5626

Answers (1)

Shuhei Kagawa
Shuhei Kagawa

Reputation: 4777

Because someMethod is a instance method. You need to instantiate the class with new to use the method.

const something = new SomeClass();
something.someMethod();

If you want to use the method without instantiating the class, you can define it as a static method.

export default class SomeClass {

    static someMethod() {
        return 1 + 1;
    }
}

SomeClass.someMethod();

In the comment above, you said that you want to use it as a callback. To use it as a callback, you may want to bind a context to the method if you use this keyword in the method. Otherwise, the this keyword doesn't point to the instance when it's called as a callback function.

var something = new SomeClass();
element.addEventListener('click', something.someMethod.bind(something));
// or
element.addEventListener('click', (event) => something.someMethod(event));

Upvotes: 7

Related Questions