为什么用关键字将其与静态方法一起使用?

时间:2019-08-12 11:13:36

标签: javascript

class StaticMethodCall {
      static staticMethod() {
        return 'Static method has been called';
      }
      static anotherStaticMethod() {
        return this.staticMethod() + ' from another static method';
      }
    }
    StaticMethodCall.staticMethod(); 
    // 'Static method has been called'

    StaticMethodCall.anotherStaticMethod(); 
    // 'Static method has been called from another static method'

为什么要这样做?在这种情况下,我之前预计会发生致命错误。

4 个答案:

答案 0 :(得分:4)

JS中的

LineNumber ---------- 15 与实际的OO语言(如Java等)中的$linenumbernew = $linenumber-1 不同。其中Java中的this指的是当前对象类,在JS中没有“类”,JS中的this只是指当前上下文范围,在您的情况下,可能是“类”上的“静态”方法,该方法本质上可以归结为成为普通旧对象的当前范围

答案 1 :(得分:1)

当您通过诸如someobject.property()之类的引用调用函数时,this的值将被设置为someobject。这是该语言的基本特征。静态方法是构造函数的属性,因此,当您通过引用构造函数调用它们时,this的值就是该函数。

答案 2 :(得分:1)

在Java之类的语言中,静态方法属于类而不是实例,因此,当您在this方法内使用static时,会收到编译错误 不知道要引用哪个实例(因为该类可能有很多实例)。

但是class只是JavaScript function对象的语法糖,因此,当您在此处调用StaticMethodCall.anotherStaticMethod();时,this将指向{{1 }} StaticMethodCall对象不过是引擎盖下的class对象。 JavaScript函数也是可以在其上声明属性的对象。因此,当您使用构造函数(es6类)时,可以在函数对象上声明属性,而这些属性只是es6中的function

让我这样解释一下,如果您通过Babel将其转换为es5,则以下代码是在后台进行的操作:

static

在这里,当您在es6类上定义//This is what static means in es6 class. they are properties of the constructor function function StaticMethodCall(){ //This represents your class } StaticMethodCall.staticMethod = function(){ return 'Static method has been called'; } StaticMethodCall.anotherStaticMethod = function(){ return this.staticMethod() + ' from another static method'; } console.log(StaticMethodCall.staticMethod()); // StaticMethodCall is a reference to the class object, this points to. console.log(StaticMethodCall.anotherStaticMethod()); 方法时,这些方法将作为构造函数的属性添加,因此,当您使用类static的引用调用静态方法时,实际上是指向该方法StaticMethodCall个对象。

因此class/function与Java中所期望的不同,在Java中您无法在静态上下文中引用this,因为它不知道要引用哪个对象(因为类不是对象) )。在Java中,类实际上不是像JavaScript这样的对象。

验证es6 this实际上是class的另一种方法是使用function

typeof

答案 3 :(得分:1)

要更好地理解它,您应该检查从 Babel

静态函数的作用域与类的作用域相同(编译的是Constructor函数)。

静态函数被声明为Constructor函数的属性,无论普通函数是否被声明为Constructor.prototype的属性,因此在所有实例上都可用。

相关问题