๐๐ถ๐ป๐ฑ
The bind method creates a new function and sets โthisโ keyword to the specified object.
๐ฌ๐๐๐๐๐๐:
const showNum= {
num: 50,
getNum: function() {
return this.num;
}
};
const unboundGetNum = showNum.getNum;
console.log(unboundGetNum());
// The function gets invoked at the global scope
// expected output: undefined
const boundGetNum= unboundGetNum.๐ฏ๐ถ๐ป๐ฑ(showNum);
console.log(boundGetNum());
// expected output: 50
๐๐๐ฅ๐ฅ
The call method sets โthisโ inside the function and immediately executes that function. Call() accepts ๐ค๐ฐ๐ฎ๐ฎ๐ข-๐ด๐ฆ๐ฑ๐ข๐ณ๐ข๐ต๐ฆ๐ฅ list of arguments.
๐ฌ๐๐๐๐๐๐:
function Gadget(name, price) {
this.name = name;
this.price = price;
}
function Laptop(name, price) {
Gadget.๐ฐ๐ฎ๐น๐น(this, name, price);
this.category = 'laptop';
}
console.log(new Laptop('Asus', 5).name);
// expected output: "Asus"
๐๐ฝ๐ฝ๐น๐
The apply() method is similar to call(). The difference is that the apply() method accepts an ๐๐๐๐๐ฆ ๐๐ ๐๐๐๐ข๐๐๐๐ก๐ instead of comma separated values.
๐ฌ๐๐๐๐๐๐:
const person = {
firstName: 'Jahid',
lastName: 'Iqbal'
}
function greet(greeting, message) {
return ${greeting} ${this.firstName} ${this.lastName}. ${message}
;
}
let result =greet.๐ฎ๐ฝ๐ฝ๐น๐(person, ['Hello', 'How are you?']);
console.log(result);
// expected output: "Hello Jahid Iqbal. How are you?"
Top comments (1)
Great blog, for those who don't know what the this keyword is by default it is:
If on a method it refers to the object owning that method
If on a regular function it will be undefined unless it is manually specified