引用静态方法内的类而不使用其名称 [英] Refer to class inside of static method without using its name

查看:57
本文介绍了引用静态方法内的类而不使用其名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用JavaScript中使用类名本身的情况下从静态方法引用类(类似于PHP的 self self :: method_name )?

How can I refer to a class from a static method without using the class name itself in JavaScript (similar to PHP's self and self::method_name)?

例如,在下面的类中,如何引用方法 foo 方法内的方法 bar ,而无需使用 FooBar.methodName

For example, in the class below, how can I refer to the method foo and the method bar inside of the foobar method without the use of FooBar.methodName?

class FooBar {
    static foo() {
        return 'foo';
    }

    static bar() {
        return 'bar';
    }

    static foobar() {
        return FooBar.foo() + FooBar.bar(); 
        // self::foo() + self::bar() would have been more desirable.
    }
}


推荐答案

您可以使用 this 关键字来引用对象本身。

You can use the this keyword to refer to the object itself.

请参见以下示例:

class FooBar {
  static foo() {
    return 'foo';
  }

  static bar() {
    return 'bar';
  }

  static foobar() {
    return this.foo() + this.bar();
    // self::foo() + self::bar() would have been more desirable.
  }
}

const res = FooBar.foobar();
console.log(res);

这篇关于引用静态方法内的类而不使用其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆