JavaScript এর this কীওয়ার্ড — বাংলা ব্যাখ্যাসহ
JavaScript-এ this একটি বিশেষ কীওয়ার্ড যা **বর্তমান কনটেক্স্ট বা অবজেক্ট** কে বোঝায়। এটি নির্ভর করে আপনি কোডটি কোথা থেকে কল করছেন।
this কখন কাকে নির্দেশ করে তা বোঝা অনেক সময় জটিল হয়। নিচে উদাহরণসহ আমরা ধাপে ধাপে শিখবো।
উদাহরণ ১: Global Scope
console.log(this);
ব্যাখ্যা: উপরের কোডটি ব্রাউজার-এ রান করলে this নির্দেশ করবে window অবজেক্ট কে।
উদাহরণ ২: একটি অবজেক্ট এর ভিতরে this
const person = {
name: "Rahim",
greet: function() {
console.log(this.name);
}
};
person.greet(); // Output: Rahim
ব্যাখ্যা: এখানে this নির্দেশ করছে person অবজেক্ট কে। তাই this.name মানে “Rahim”।
উদাহরণ ৩: Function এর ভিতরে this
function show() {
console.log(this);
}
show();
ব্যাখ্যা: ব্রাউজার-এ রান করলে, এখানে this হবে window। কারণ এটি সাধারণ ফাংশন হিসেবে কল হয়েছে।
উদাহরণ ৪: Constructor Function এ this
function Car(brand) {
this.brand = brand;
}
const myCar = new Car("Toyota");
console.log(myCar.brand); // Output: Toyota
ব্যাখ্যা: এখানে this নির্দেশ করছে নতুন তৈরি হওয়া অবজেক্ট myCar কে।
উদাহরণ ৫: Arrow Function এর ভিতরে this
const user = {
name: "Karim",
sayHi: () => {
console.log(this.name);
}
};
user.sayHi(); // Output: undefined
ব্যাখ্যা: Arrow function এ this bind হয় না। এটি উপরের স্কোপ থেকে this নেয়। তাই এখানে this.name undefined হবে।
উপসংহার:
this কী নির্দেশ করবে তা নির্ভর করে আপনি কোডটা কোথা থেকে কল করছেন:
| Context | this কী নির্দেশ করে |
|---|---|
| Global (Browser) | window |
| Object Method | That Object |
| Constructor Function | New Created Object |
| Arrow Function | Parent Context |