无法在Javascript中通过对象调用静态方法

时间:2018-05-21 12:28:49

标签: javascript ecmascript-6

class staticClass{
     static myMethod(){
         return 'My Method';
     }

     method2(){return 'Method 2';}
}

var s = new staticClass();
console.log(s.method2()); // 'Method 2'

console.log(staticClass.myMethod()); // 'My Method'

console.log(s.myMethod()); // 's.myMethod is not a function'

为什么我们无法通过Javascript中的对象访问静态方法

在Java中,我们可以通过对象访问静态方法。他们是不同的语言是的,但这个设计背后有任何理由

1 个答案:

答案 0 :(得分:1)

您可以在实例上通过constructor属性调用静态方法。



class staticClass {
  static myMethod() {
    return 'My Method';
  }

  method2() {
    return 'Method 2';
  }
}

var s = new staticClass();
console.log(s.method2());
console.log(staticClass.myMethod());

console.log(s.constructor.myMethod());