【问题标题】:Calling super methods inside separate scope在单独的范围内调用超级方法
【发布时间】:2015-09-22 07:11:01
【问题描述】:

我正在尝试从不同范围内调用 super 方法,但这似乎不起作用。

'use strict';

class One {
    test() {
        console.log('test');
    }
 }

class Two extends One {
    hi() {
        super.test();
    }
    hello() {
        var msg = 'test';
        return new Promise(function(resolve, reject) {
             console.log(msg);
             super.test();
        });
    }
}

var two = new Two();
two.hi();
two.hello();

【问题讨论】:

  • 您没有在 CodePen 上设置预处理器,因此它正在尝试使用浏览器中可能缺少的 ES6 功能。将 JavaScript 预处理器设置为 Babel
  • @RGraham 虽然这在 CodePen 中有效,但我在 Node 应用程序中运行它。 (v4.0.0)
  • 对不起,我以为你在谈论演示,我现在看到了标签。也许 Babel 不能转换这个并且 NodeJS 表现出正确的行为。好问题 - 我会删除你的演示 :)
  • 我删除了它,因为它只是半正确的。更改预处理器确实在codepen中解决了它。你有任何关于 ES6 中super 范围的资料吗?我真的找不到任何有明确答案的东西。
  • @ralh Found it (down atm, Google for cached version) Babel 错了,Node 的实现(和你的答案)是正确的

标签: javascript node.js ecmascript-6


【解决方案1】:

显然,在 Babel 中,它开箱即用。但在节点中,似乎在该匿名函数中,this 不再绑定到 two 对象,并且 super 那时不可用。您可以使用粗箭头将this 绑定到匿名函数的范围:

return new Promise((resolve, reject) => {
    console.log('Message: ', msg);
    super.test();
});

如果您不熟悉粗箭头和/或this 作用域的概念,请阅读以下内容: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 2013-12-08
    • 2014-01-04
    • 2016-02-18
    • 2023-03-15
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多