6 kyu

Java-like static method in JS

147 of 148BruceLee

Description:

Many of Object Oriented languages offer the feature of static methods, which can be called by both classes themselves and their instances. For example, we can write the following class in Java:

class Test {
  public static void foo() {
    // doing things
  }
}

After that, we can use both class Test and its instances to call static method foo():

Test.foo(); or new Test().foo();

In JavaScript, we can create classes too:

class Class {
  static staticProperty = 666;
  instanceProperty = 777;

  static staticMethod () {
    console.log(Class.staticProperty);
  }

  instanceMethod() {
    console.log(this.instanceProperty);
  }
}
const obj = new Class();
obj.instanceMethod(); // 666
Class.staticMethod(); // 777

Your Mission:

Implement a function addStaticMethod which takes a class (e.g.: Class), a name (e.g.: 'foo'), and a method (function) as arguments. It will add the method reference to the class with a specified name, as one of its static methods.

The added static method should be able to be called by the class and its instances, just like what happens in Java.

class Class {
  static property = 'static';
  property = 'instance';
}

const obj = new Class();

Class.property; // 'static'
obj.property;  // 'instance'

addStaticMethod(Class, 'foo', function () { return this.property; });

Class.foo(); // 'static'
obj.foo();   // 'static'

Note: Look at this carefully! (It's a hint rather than a note)

Puzzles

More By Author:

Check out these other kata created by BruceLee

Stats:

CreatedOct 11, 2015
PublishedOct 11, 2015
Warriors Trained345
Total Skips9
Total Code Submissions1421
Total Times Completed148
JavaScript Completions147
Total Stars15
% of votes with a positive feedback rating91% of 44
Total "Very Satisfied" Votes37
Total "Somewhat Satisfied" Votes6
Total "Not Satisfied" Votes1
Total Rank Assessments12
Average Assessed Rank
5 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
6 kyu
Ad
Contributors
  • BruceLee Avatar
  • aweleshetu Avatar
  • Souzooka Avatar
  • trashy_incel Avatar
Ad