this কীওয়ার্ড
জাভাস্ক্রিপ্টে this কীওয়ার্ডটি একটি রেফারেন্স হিসেবে কাজ করে যা এক্সিকিউট হচ্ছে কোডের অবজেক্ট বা সাবজেক্টকে নির্দেশ করে।
উদাহরণ
<script>
var college = {
subject: "Maths",
lecturer: "Amy",
details: function() {
document.write(this.subject);
}
};
</script>
this বাইন্ডিং নিয়মাবলী
| কল টাইপ | this বাইন্ড होता | উদাহরণ |
|---|---|---|
| গ্লোবাল স্কোপ | window (ব্রাউজার) / global (Node) | console.log(this); // window |
| ফাংশন কল (non-strict) | window / global | func(); // this = window |
| ফাংশন কল (strict) | undefined | "use strict"; func(); // this = undefined |
| মেথড কল | অবজেক্ট (owner) | obj.method(); // this = obj |
| কনস্ট্রাক্টর (new) | নতুন ইনস্ট্যান্স | new MyClass(); // this = new instance |
| call/apply/bind | এক্সপ্লিসিট আর্গুমেন্ট | func.call(obj); // this = obj |
| অ্যারো ফাংশন | লেক্সিক্যাল (পেরেন্ট স্কোপ) | () => this; // enclosing scope |
সাধারণ সমস্যা এবং সমাধান
var obj = {
value: 42,
getValue: function() {
return function() {
return this.value; // this = window/undefined
};
}
};
// সমাধান ১: Arrow function
getValue: function() {
return () => this.value; // this = obj
}
// সমাধান ২: bind
getValue: function() {
return function() { return this.value; }.bind(this);
}
// সমাধান ৩: self/that ভেরিয়েবল
getValue: function() {
var self = this;
return function() { return self.value; };
}