Java-like static method in JS
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)
Similar Kata:
Stats:
Created | Oct 11, 2015 |
Published | Oct 11, 2015 |
Warriors Trained | 345 |
Total Skips | 9 |
Total Code Submissions | 1421 |
Total Times Completed | 148 |
JavaScript Completions | 147 |
Total Stars | 15 |
% of votes with a positive feedback rating | 91% of 44 |
Total "Very Satisfied" Votes | 37 |
Total "Somewhat Satisfied" Votes | 6 |
Total "Not Satisfied" Votes | 1 |
Total Rank Assessments | 12 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 5 kyu |
Lowest Assessed Rank | 6 kyu |