Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using a JavaScript object inside a static() method?
In JavaScript, static methods belong to the class itself, not to instances. You cannot directly access instance objects or use this inside static methods. However, you can pass objects as parameters to static methods to access their properties.
Problem: Direct Object Access in Static Methods
In the following example, trying to call a static method on an instance will result in an error because static methods should be called on the class, not the instance.
<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");
// This will cause an error - calling static method on instance
document.getElementById("method").innerHTML = myComp.comp();
</script>
</body>
</html>
This code produces an error: "myComp.comp is not a function" because static methods cannot be called on instances.
Solution: Passing Objects as Parameters
The correct approach is to call the static method on the class and pass the object instance as a parameter:
<html>
<body>
<p id="method"></p>
<script>
class Company {
constructor(branch) {
this.name = branch;
}
static comp(val) {
return "Elon musk is the head of " + val.name;
}
}
myComp = new Company("Tesla");
document.getElementById("method").innerHTML = Company.comp(myComp);
</script>
</body>
</html>
Output
Elon musk is the head of Tesla
Key Points
- Static methods are called on the class, not on instances:
Company.comp() - Static methods cannot access
thisor instance properties directly - To work with object data in static methods, pass the object as a parameter
- Calling static methods on instances will result in errors
Conclusion
Static methods in JavaScript cannot directly access instance objects. Always call static methods on the class itself and pass objects as parameters when you need to access their properties.
