【问题标题】:NodeJs/Javascript access parent method in nested class [duplicate]NodeJs / Javascript访问嵌套类中的父方法[重复]
【发布时间】:2015-11-16 06:25:48
【问题描述】:
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   
});

【问题讨论】:

  • 为什么人们总是写“EC6”?该术语在任何地方都使用过吗?
  • 我只是简写了Ecmacript 6,不知道是否常用。
  • 标准缩写是 ES6(来自ECMA-Script)。我只是想知道,因为我现在已经多次看到“EC6”,而它真的没有意义:-)
  • 好的,谢谢你提到这一点,我以后会使用正确的缩写:)

标签: javascript node.js class ecmascript-6 eventemitter


【解决方案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 关键字解析为定义函数的实例。

【讨论】:

    【解决方案2】:

    您在 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');
    });
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2010-11-09
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2017-11-12
      • 2011-06-12
      • 1970-01-01
      相关资源
      最近更新 更多