Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Class Static

JS Class Static Methods

Static class methods are defined on the class itself. You cannot call a static method on an object, only on an object class.

Example
					 
        
          class Car {
            constructor(name) {
              this.name = name;
            }
            static hello() {
              return "Hello!!";
            }
          }

          const myCar = new Car("Ford");

          // You can call 'hello()' on the Car Class:
          document.getElementById("demo").innerHTML = Car.hello();

          // But NOT on a Car Object:
          // document.getElementById("demo").innerHTML = myCar.hello();
          // this will raise an error.
        
      

If you want to use the myCar object inside the static method, you can send it as a parameter.

Example
					 
        
          class Car {
            constructor(name) {
              this.name = name;
            }
            static hello(x) {
              return "Hello " + x.name;
            }
          }
          const myCar = new Car("Ford");
          document.getElementById("demo").innerHTML = Car.hello(myCar);
        
      

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved