Saturday 20 October 2018

JavaScript: Adding static methods to a class

Static methods are defined using ‘static’ keyword. Static methods are called without instantiating the class.

Syntax to call static method
ClassName.methodName(arguments)

HelloWorld.js
class InterestCalc{
  
  constructor(principle, time, rateOfInterest){
    this.principle = principle;
    this.time = time;
    this.rateofInterest = rateOfInterest;
  }

  static getInterest(Interest){
    var Interest = (Interest.principle * Interest.time * Interest.rateofInterest) / 100;
    return Interest;
  }
}

var obj1 = new InterestCalc(1000, 5, 2);
var interest = InterestCalc.getInterest(obj1);

console.log("Interest is : " + interest);

Output
Interest is : 100


Previous                                                 Next                                                 Home

No comments:

Post a Comment