ফ্যাট অ্যারো ফাংশন এবং লেক্সিক্যাল this
ফ্যাট অ্যারো ফাংশন (=>) this-এর লেক্সিক্যাল বাইন্ডিং সমস্যা সমাধান করে। এটি পেরেন্ট স্কোপের this কনটেক্স্ট গ্রহণ করে, কারণ অ্যারো ফাংশনের নিজস্ব this নেই।
সমস্যা: রেগুলার ফাংশনে this
$('.button1').click(function() {
setTimeout(function() {
$(this).text('demo'); // ❌ this = window (গ্লোবাল)
}, 400);
});
সমাধান: ফ্যাট অ্যারো ফাংশন
$('.button1').click(function() {
setTimeout(() => {
$(this).text('demo'); // ✅ this = .button1 এলিমেন্ট
}, 400);
});
লেক্সিক্যাল স্কোপিং ব্যাখ্যা
const obj = {
value: 42,
regularFunc: function() {
console.log(this.value); // 42
// নেস্টেড রেগুলার ফাংশন
function inner() {
console.log(this.value); // undefined (this = window/undefined)
}
inner();
// নেস্টেড অ্যারো ফাংশন
const arrow = () => {
console.log(this.value); // 42 (লেক্সিক্যাল this)
};
arrow();
}
};
obj.regularFunc();
অ্যারো ফাংশনের সীমাবদ্ধতা
thisবাইন্ড করা যায় না (call,apply,bindকাজ করে না)argumentsঅবজেক্ট নেই (rest parameters...argsব্যবহার করুন)- কনস্ট্রাক্টর হিসেবে ব্যবহার করা যায় না (
newদিয়ে কল করা যায় না) prototypeপ্রোপার্টি নেই