জাভাস্ক্রিপ্টে, this সেই অবজেক্টকে নির্দেশ করে যেটি বর্তমান ফাংশন এক্সিকিউট করছে।
this-এর মান ফাংশনটি কীভাবে কল করা হচ্ছে তার উপর নির্ভর করে, এটি কোথায় লেখা হয়েছে তার উপর নয়।
গ্লোবাল স্কোপে, this গ্লোবাল অবজেক্টকে নির্দেশ করে।
window।console.log(this); // windowএকটি অবজেক্ট মেথডে ব্যবহার করা হলে, this অবজেক্টটিকেই নির্দেশ করে।
const person = {
name: "Alice",
greet() {
console.log("Hello, I'm " + this.name);
},
};
person.greet(); // "Hello, I'm Alice"this.name, person.name-কে নির্দেশ করে।
const person = {
name: "Alice",
greet() {
console.log(this.name);
},
};
const sayHello = person.greet;
sayHello(); // undefined (নন-স্ট্রিক্ট মোডে) বা এরর (স্ট্রিক্ট মোডে)this বাইন্ড করা নেই, তাই এটি গ্লোবাল অবজেক্ট বা স্ট্রিক্ট মোডে undefined-কে নির্দেশ করে।
const person = {
name: "Bob",
};
function greet() {
console.log("Hello, " + this.name);
}
greet.call(person); // "Hello, Bob"
greet.apply(person); // "Hello, Bob"
const greetPerson = greet.bind(person);
greetPerson(); // "Hello, Bob"call() এবং apply() একটি নতুন this পাস করে ফাংশনটি সাথে সাথে কল করে।bind() বাইন্ড করা this-সহ একটি নতুন ফাংশন রিটার্ন করে।একটি কনস্ট্রাক্টর ফাংশনে, this নতুন তৈরি হওয়া অবজেক্টকে নির্দেশ করে।
function Car(brand) {
this.brand = brand;
}
const myCar = new Car("Toyota");
console.log(myCar.brand); // "Toyota"অ্যারো ফাংশনের নিজস্ব this থাকে না। এগুলো তাদের parent scope থেকে this ইনহেরিট করে।
const user = {
name: "Alice",
greet: () => {
console.log(this.name); // undefined
},
};
user.greet();আশেপাশের this সংরক্ষণ করতে চাইলে অ্যারো ফাংশন দারুণ কাজে দেয়।
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
new Timer(); // সঠিকভাবে সেকেন্ড লগ করে| প্রসঙ্গ (Context) | this নির্দেশ করে |
|---|---|
| গ্লোবাল স্কোপ | গ্লোবাল অবজেক্ট (window) |
| অবজেক্ট মেথড | অবজেক্টটি নিজেই |
| ফাংশন (নন-মেথড) কল | গ্লোবাল অবজেক্ট বা undefined (স্ট্রিক্ট) |
| কনস্ট্রাক্টর ফাংশন | নতুন তৈরি হওয়া অবজেক্ট |
| অ্যারো ফাংশন | বাইরের স্কোপ থেকে this ইনহেরিট করে |
bind(), call(), apply()-সহ | ম্যানুয়ালি নির্ধারিত অবজেক্ট |
this ব্যবহার করুন।this লক্ষ্য করুন।this ঠিক করতে bind() ব্যবহার করুন।this সংরক্ষণ করতে setTimeout-এর ভেতরে অ্যারো ফাংশন ব্যবহার করুন।this ব্যবহার করে প্রপার্টি সেট করে এমন একটি কনস্ট্রাক্টর তৈরি করুন।