简体   繁体   中英

ES6 classes, with parent in different file, and node.js?

What is the right way to use a class defined in one file and extend it another, in node.js?

Currently I have:

'use strict'

class BasePageHandler {

    constructor(app, settings, context) {

    }
}

return module.exports;

In the 'child' class file I have:

'use strict'

var BasePageHandler = require ('./../BasePageHandler.js');

class FrontpagePageHandler extends BasePageHandler {
    constructor(app, settings, context) {
         super(app, settings, context);
         this.settings = settings;
         this.context = context;
    }
}

This fails with the following error:

TypeError: Class extends value #<Object> is not a function or null

Note, if I have the BasePageHandler in the same file then it works, so it is really when the class is in another file I have an issue.

Currently using node 4.4.0.

您需要在BasePageHandler.js文件中正确导出您的类:

module.exports = BasePageHandler;

The accepted answer is technically fine, but really if you're using ES6 then you should go all in and use ES6 export/import .

/*jshint esversion: 6 */

class BasePageHandler {
    constructor(app, settings, context) {
    }
}

export default BasePageHandler;

and then:

/*jshint esversion: 6 */

import BasePageHandler from './../BasePageHandler.js';

class FrontpagePageHandler extends BasePageHandler {
    constructor(app, settings, context) {
         super(app, settings, context);
         this.settings = settings;
         this.context = context;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM