DEV Community

Cover image for ๐๐ข๐ง๐, ๐‚๐š๐ฅ๐ฅ, ๐š๐ง๐ ๐€๐ฉ๐ฉ๐ฅ๐ฒ ๐Œ๐ž๐ญ๐ก๐จ๐๐ฌ ๐ข๐ง ๐‰๐š๐ฏ๐š๐’๐œ๐ซ๐ข๐ฉ๐ญ
Jahid Iqbal
Jahid Iqbal

Posted on

๐๐ข๐ง๐, ๐‚๐š๐ฅ๐ฅ, ๐š๐ง๐ ๐€๐ฉ๐ฉ๐ฅ๐ฒ ๐Œ๐ž๐ญ๐ก๐จ๐๐ฌ ๐ข๐ง ๐‰๐š๐ฏ๐š๐’๐œ๐ซ๐ข๐ฉ๐ญ

๐—•๐—ถ๐—ป๐—ฑ
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)

Collapse
 
hacker4world profile image
hacker4world

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