Using a JavaScript object inside a static() method?

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

<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
raja
Published on 02-Aug-2019 17:41:16
Advertisements