

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Static methods in JavaScript classes?
Static methods
Using static methods, we can access only the elements in a class but not the elements in the object. It is possible to call a static method only inside a class but not in an object.
Example-1
In the following example, static() method is initiated in class "Company" rather than in an object "myComp". Therefore the contents in the static() method were executed in the output.
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } static comp() { return "Tutorix is the best e-learning platform" } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = Company.comp(); </script> </body> </html>
Output
Tutorix is the best e-learning platform
Example-2
In the following example, instead of the class, the object is called therefore no output will be executed. If we open the browser console we can see an error stating that "myComp.comp()" is not a function.
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } static comp() { return "Tutorix is the best e-learning platform" } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = myComp.comp(); </script> </body> </html>
- Related Questions & Answers
- Static Nested Classes in Java
- What is the difference between static classes and non-static inner classes in Java?
- Static methods vs Instance methods in Java
- Differences between static and non-static methods in Java
- How to assign static methods to a class in JavaScript?
- PHP Static Properties and Methods
- Kotlin static methods and variables
- Are static methods inherited in Java?
- Java 8 static methods in interfaces
- Shadowing of static methods in Java
- Restrictions applied to Java static methods
- When to use static methods in Java?
- Can I overload static methods in Java?
- Can interfaces have Static methods in Java?
- What are Class/Static methods in Java?
Advertisements