class Foo extends EventEmitter {
constructor(name) {
this.name = name;
}
funcA(sourceRepositoryPath, branch) {
this.emit('log', 'Hello from Foo');
var bar = new Bar();
bar.on('log', function(log) {
this.emits('log', 'Hello from Foo from Bar');
});
}
}
如何在bar.on ...函数中使用Foo中的emit函数,如
this.emit('log', 'Hello from Foo');
ES6中的功能?
var foo = new Foo();
foo.funcA();
foo.on('log', function(log) {
// expects : Hello from Foo && Hello from Foo from Bar
// gets : Hello From Foo
});
答案 0 :(得分:1)
bar.on()处理程序中有不同的上下文,因此您需要将其绑定到外部作用域:
bar.on('log', function(log) {
this.emits('log', 'Hello from Foo from Bar');
}.bind(this));
或保留对它的引用:
var self = this;
bar.on('log', function(log) {
self.emits('log', 'Hello from Foo from Bar');
});
或者当您使用ES6 / ES2015时,您可以使用箭头功能来保持外部绑定(并且您的转换器将为您执行上述操作之一):
bar.on('log', (log) => {
self.emits('log', 'Hello from Foo from Bar');
});
希望它有所帮助!
答案 1 :(得分:1)
箭头函数语法解决了这个确切的问题:
class Foo extends EventEmitter {
constructor(name) {
this.name = name;
}
funcA(sourceRepositoryPath, branch) {
this.emit('log', 'Hello from Foo');
var bar = new Bar();
bar.on('log', (log) => {
this.emits('log', 'Hello from Foo from Bar');
});
}
}
除了更简洁,更简洁的语法之外,箭头函数定义了一个词法this
",这意味着箭头函数中的this
关键字解析为函数所在的实例是定义。