不能用ES6 / babel-node子类化

时间:2015-09-24 08:47:03

标签: node.js ecmascript-6 babeljs

我有以下文件:gist

index.js 尝试实例化一个基类“Auth”类,但在其构造函数中,auth类充当对象工厂并转而返回Auth的子类。

'use strict';
import Auth from './Auth';

let o = new Auth({type:'Oauth1'});
console.log(o);
o.getToken();

Auth.js 类定义如下:

'use strict';
import Oauth1 from './Oauth1';

export default class Auth {
    constructor(config) {
        if (this instanceof Auth) {
            return new Oauth1(config);
        } else {
            this.config = config;
        }
    }

    getToken() {
        console.log('Error: the getToken module must be implemented in the subclass');
    }
}

Oauth1.js 类定义是:

'use strict';
import Auth from './Auth';

export default class Oauth1 extends Auth {
    getToken() {
        console.log('Auth: ', Auth);
    }
}

使用babel-node index.js运行时出现以下错误:

  

TypeError :超级表达式必须为null或函数,而不是未定义

at _inherits (/repos/mine/test-app/Oauth1.js:1:14)
at /repos/mine/test-app/Oauth1.js:4:28
at Object.<anonymous> (/repos/mine/test-app/Oauth1.js:4:28)
at Module._compile (module.js:434:26)
at normalLoader (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)

如果我从它执行的Oauth1类中删除extends表达式,但是我没有得到我想要的继承。

1 个答案:

答案 0 :(得分:3)

您的问题与babel无关。真正的问题是您的代码中有circular dependencies

要解决此问题,您应该从其父Oauth1类中删除Auth依赖项:

'use strict';
export default class Auth {
    constructor(config) {
        this.config = config;
    }

    getToken() {
        console.log('Error: the getToken module must be implemented in the subclass');
    }
}
'use strict';
import Auth from './Auth';

export default class Oauth1 extends Auth {
    getToken() {
        console.log('Auth: ', Auth);
    }
}

如果您不想从基类中删除this instanceof Auth检查,则可以在运行时require Oauth1子类,而不是在模块初始化期间导入它:

constructor(config) {
    if (this instanceof Auth) {
        let Oauth1 = require('./Oauth1');
        return new Oauth1(config);
    }
    this.config = config;
}