DEV Community

Cover image for Don't mind it, Bind it Re
abhi
abhi

Posted on

Don't mind it, Bind it Re

I have been struggle a lot in order to understand the concept of this,bind,apply and call concepts of javascript.Since I am from Java Background this keyword was bit confusing.

Here I will explain about call method in neat and clean way....
let's say we have array of objects and wants to apply some method on each and every object
in traditional way we will iterate array and call method and pass argument for every object.

var list = [{ length: 20, breadth: 22 }, { length: 5, breadth: 6 },{ length: 12, breadth: 8 }, { length: 13, breadth: 9 },
{ length: 7, breadth: 4 }];
function calculateAreaRectangle(length,breadth) {
console.log(length * breadth);
}
list.forEach(element => {
calculateAreaRectangle(element.length,element.breadth);
})

In this example we are calling calculateAreaRectangle() method on each and every obejct by query every object and getting length and breadth.

It can be done by just passing object which will be refernced as this in calculateAreaRectangle() and inside calculateAreaRectangle use this.length*this.breadth and it will do the same
below example will describe it

var list = [{ length: 20, breadth: 22 }, { length: 5, breadth: 6 },{ length: 12, breadth: 8 }, { length: 13, breadth: 9 },{ length: 7, breadth: 4 }];
function calculateAreaRectangle() {
console.log(this.length * this.breadth);
}
list.forEach(element => {
calculateAreaRectangle.call(element);
})

Alt Text
Now let's discuss about THIS keyword we are going to use same example along with global variable length and breadth...

var length = 3;
var breadth = 2;
var list = [{ length: 20, breadth: 22 }, { length: 5, breadth: 6 }, { length: 12, breadth: 8 }, { length: 13, breadth: 9 },
{ length: 7, breadth: 4 }];
function calculateAreaRectangle() {
console.log(this.length * this.breadth);
}
calculateAreaRectangle(); // it will produce output of 6 because when we will call it will consider global variable as this and since we have length and breadth in global scope it will
calculate and log result, if there is no variable with name of length and breadth in global scope it will throw NaN.
list.forEach(element => {
calculateAreaRectangle.call(element);
})

THANKS FOR READING

Top comments (0)