బాణం విధులు చిన్నవి, కానీ నిజమైన తేడాలు బైండింగ్ ప్రవర్తనలో ఉన్నాయి, కేవలం సింటాక్స్లో కాదు.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
బాణం విధులు చిన్నవి, కానీ నిజమైన తేడాలు బైండింగ్ ప్రవర్తనలో ఉన్నాయి, కేవలం సింటాక్స్లో కాదు.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. స్వంత this లేదు — బాణాలు చుట్టుపక్కల స్కోప్ నుండి this ను పొందుపరుస్తాయి. ఇది అత్యంత ముఖ్యమైన వ్యత్యాసం మరియు అవి callbacks కోసం ఎందుకు గొప్పవి:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. arguments ఆబ్జెక్ట్ లేదు — బదులుగా rest parameters ను ఉపయోగించండి:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Constructors గా ఉపయోగించబడవు — new arrow() విసిరి వేస్తుంది, మరియు వాటికి prototype లేదు.
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
object methods కోసం బాణాలను ఉపయోగించవద్దు (అవి ఆబ్జెక్ట్కు బైండ్ చేయబడవు) లేదా మీకు dynamic this/arguments అవసరమైనప్పుడు (ఈవెంట్ హ్యాండ్లర్లు this ఎలిమెంట్గా ఉండటంపై ఆధారపడతాయి).
Callbacks మరియు చిన్న విధుల కోసం బాణాలను ఉపయోగించండి ఇక్కడ this ను పొందుపరచడం మీకు కావలసినది; methods, constructors, మరియు prototype methods కోసం సాధారణ విధులను ఉపయోగించండి.
జూనియర్ నుండి సీనియర్ వరకు వివరణాత్మక సమాధానాలతో IT ఇంటర్వ్యూ ప్రశ్నల లైబ్రరీ.
విరాళం