- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using a JavaScript object inside a static() method?
Actually, the result will be in vain when we try to use an object inside a static method. But when the object is sent as a parameter, we can access the object. let's discuss it in a nutshell.
Example-1
In the following example, we tried to use the object "myComp" directly rather than sending it as a parameter, therefore, we get no result. If we open the browser console we will get an error that is "myComp.comp() is not a function". To get the actual result we have to send the object as a parameter as shown in Example-2
<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>
Example-2
In the following example, the object is sent as a parameter. Therefore we will get as shown in the output.
<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
Advertisements