扩展EventEmitter时如何解决"这未定义"?

guy*_*abi 8 javascript class node.js ecmascript-6

以下代码失败:

var EventEmitter = require('events'); 

class Foo extends EventEmitter{
    constructor(){
        this.name = 'foo';
    }
    print(){
        this.name = 'hello';
        console.log('world');
    }
}
var f = new Foo();
console.log(f.print());
Run Code Online (Sandbox Code Playgroud)

并打印错误

 this.name = 'foo';
    ^

ReferenceError: this is not defined
Run Code Online (Sandbox Code Playgroud)

但是当我没有扩展EventEmitter时它工作正常.

为什么会发生这种情况,我该如何解决?运行nodejs 4.2.1

the*_*eye 18

当你扩展另一个函数时,那么super(..)应该是你的第一个表达式constructor.只有这样你才能使用this.

var EventEmitter = require('events');

class Foo extends EventEmitter {
    constructor() {
        super();
        this.name = 'foo';
    }
    print() {
        console.log(this.name);
    }
}

new Foo().print();
// foo
Run Code Online (Sandbox Code Playgroud)

它是这样的,因为在你当前的类覆盖它们之前,应该给你一个机会来设置变量.

此外,隐式调用super()意味着,我们将传递undefinedconstructor在父类中声明的参数.这就是默认情况下没有完成的原因.