Can i chain static methods in javascript ? here's what an example for what i am trying to do
test.js
'use strict'
class testModel{
static a(){
return "something that will be used in next method"
}
static b(){
let previousMethodData = "previous method data"
return "data that has been modified by b() method"
}
}
module.exports = testModel
then i want to be able to called the methods like this
const value = testModel.a().b()
Others have explained in the comments that you want the methods a()
and b()
to be instance methods rather than static methods so that you can manipulate the value of this
.
In order to have the static chaining that you want, only the first method in the chain needs to be static. You can call a static method like create()
that returns an instance, and then subsequent functions in the chain can be called on that instance. Here's a simple example:
class TestModel {
constructor() {
this.data = {};
}
static create() {
return new TestModel();
}
a() {
this.data.a = true;
return this;
}
b() {
this.data.b = true;
return this;
}
final() {
return this.data;
}
}
console.log(TestModel.create().a().b().final()); // => {"a": true, "b": true}
console.log(TestModel.create().a().final()); // => {"a": true}
console.log(TestModel.create().b().final()); // => {"b": true}