C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript static MethodThe JavaScript provides static methods that belong to the class instead of an instance of that class. So, an instance is not required to call the static method. These methods are called directly on the class itself. Points to remember
JavaScript static Method Example 1Let's see a simple example of a static method. <script> class Test { static display() { return "static method is invoked" } } document.writeln(Test.display()); </script> Output: static method is invoked Example 2Le's see an example to invoke more than one static method. <script> class Test { static display1() { return "static method is invoked" } static display2() { return "static method is invoked again" } } document.writeln(Test.display1()+"<br>"); document.writeln(Test.display2()); </script> Output: static method is invoked static method is invoked again Example 3Let's see an example to invoke more than one static method with similar names. <script> class Test { static display() { return "static method is invoked" } static display() { return "static method is invoked again" } } document.writeln(Test.display()); </script> Output: static method is invoked again Example 4Let's see an example to invoke a static method within the constructor. <script> class Test { constructor() { document.writeln(Test.display()+"<br>"); document.writeln(this.constructor.display()); } static display() { return "static method is invoked" } } var t=new Test(); </script> Output: static method is invoked static method is invoked Example 5Let's see an example to invoke a static method within the non-static method. <script> class Test { static display() { return "static method is invoked" } show() { document.writeln(Test.display()+"<br>"); } } var t=new Test(); t.show(); </script> Output: static method is invoked
Next TopicJS Encapsulation
|