0
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'

Why are we not able to access static methods via an object in Javascript

In Java we can access static methods via objects. They are different languages yes, but is there any reason behind this design

2
  • 6
    The whole point of the function being static is that it isn't attached to an instance. Why do you want to call it like s.myMethod() instead of staticClass.myMethod()? Commented May 21, 2018 at 12:32
  • Java is weird. What's the reason behind their design? Commented May 21, 2018 at 13:12

1 Answer 1

1

You could call static method by constructor property on instance.

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

Sign up to request clarification or add additional context in comments.

1 Comment

it does not work for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.