Method chaining in javascript
ISIAKA ABDULAHI AKINKUNMI
Posted on April 19, 2021
Method is a function that is a property of an object. It is also a property containing a function definition.
let's consider the example below
Var car = {
Color: “red”,
brand: “Toyota”,
description: function (){
This.brand + "is a Motor Corporation is a Japanese multinational automotive manufacturer"
}
}
// description is a property of a car that is also a function. So a function inside an object is called METHOD.
//Calling
console.log(car.description())
// Toyota is a Motor Corporation is a Japanese multinational automotive manufacturer
If we have 5 methods in the object. We end up with something like this:
car.description()
car.description()
car.description()
car.description()
car.description()
Could you see that car
is unnecessarily repeated and doesn’t seems neat and could take lines of code? We can get rid of that by using a mechanism called METHOD CHAINING.
Method chaining is the mechanism of calling a method on another method of the same object. This ensures a cleaner and readable code. Method chaining uses this
keyword in the object's class to access its methods. In javascript, the this
keyword refers to the current object in which it is called. When a method returns this
, it simply returns an instance of the object in which it is returned. in another word, to chain methods together, we need to make sure that each method we define has a return value so that we can call another method on it.
Let's write some code
Class chaining{
Method1(){
console.log(method1)
return this
}
Method2(){
console.log(method2)
return this
}
}
Const chaining_obj = new chaining()
chaining_obj
.mathod1()
.method2()
//output
method1
method2
let's consider this example
class Arithmetic {
constructor() {
this.value = 0;
}
sum(...args) {
this.value = args.reduce((sum, current) => sum + current, 0);
return this;
}
addition(value) {
this.value = this.value + value;
return this;
}
subtraction(value) {
this.value = this.value - value;
return this;
}
average(...args) {
this.value = args.length? (this.sum(...args).value) /
args.length: undefined;
return this;
}
}
const Arithmetic 1= new Arithmetic()
Arithmetic1
.sum(1, 3, 6) // => { value: 10 }
.subtraction(3) // => { value: 7 }
.add(4) // => { value: 11 }
.value // => 11
Thanks for reading
Do you wish to get notified when I published a new article? click here
Posted on April 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.