What is role of static method in JS?

Asked 19-Jul-2021
Viewed 310 times

1 Answer


0

the static keyword defines the static method and property of a class without static function or property is called instance method or property of the class, a static property is useful for the cache. if we create the global variable, This will be there as long as the program is running.

Syntax
class class-name{
 constructor(){
  //statement
 }
static propertyName [= value];
 static method-name( [arguments] ){   //statement  } }

Example 

<!DOCTYPE html>

<html>
<style>
 p{
    font-size:25px;
    }
</style>
<body>
<h2>My Heading</h2>
<p id='demo'></p>
<script>
class Person {
 constructor(name) {
  this.name = name;
 }
 //normal function
 getName() {
  return this.name;
 }
 //static function
 static createAnonymous(org) {
  let name = org == 'org' ? 'MindStick Software pvt ltd' : 'Uttam Misra';
  return new Person(name);
 }
}
let anonymous = Person.createAnonymous('org');
document.getElementById('demo').innerHTML = anonymous.name;
</script>
</body>
</html>    

Output 

My Heading

MindStick Software pvt ltd