本文介绍了在单独的范围内调用超级方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to call a super method from inside a different scope, but this doesn't appear to be working.

'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();


推荐答案

显然,在Babel中, 。在节点中,似乎在该匿名函数中,不再绑定到两个对象和 super 不可用。您可以使用胖箭头将绑定到匿名函数的范围:

Apparently, in Babel it works right out of the box. In node though, it appears that in that anonymous function, this is no longer bound to the two object and super is not available then. You can use a fat arrow to bind this to the scope of the anonymous function:

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

如果您不熟悉胖箭头和/或这个范围,这是一个很好的阅读:

If you're not familiar with the concept of fat arrows and/or this scope, this is a good read:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这篇关于在单独的范围内调用超级方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:41