JS का this Keyword
In this page:
this.property
const object = {
method() {
return this; // the object
}
};
Object में this
किसी object method के अंदर, this आमतौर पर उस object को refer करता है जिसने method को कॉल किया।
अगर वही method बाद में किसी दूसरे object को assign किया जाए या standalone कॉल किया जाए, तो this उसी हिसाब से बदल जाता है क्योंकि यह call से तय होता है, न कि इससे कि function कहाँ define किया गया था।
उदाहरण: this in an Object
const user = {
name: "Sam",
greet() {
console.log(this.name);
},
};
user.greet(); // this === user
Regular Function में this
किसी regular function में this की value इस पर निर्भर करती है कि function को कैसे कॉल किया गया। strict mode में, एक plain function call में this undefined होता है।
non-strict mode में, वही plain call इसके बजाय this को global object पर default कर देता है, जो एक कारण है कि strict mode के ज़्यादा सख्त व्यवहार को आमतौर पर prefer किया जाता है।
उदाहरण: this in a Regular Function
function show() {
"use strict";
console.log(this); // undefined in strict mode
}
show();
Arrow Functions में this
Arrow functions अपना खुद का this नहीं बनाते। वे surrounding scope से this इस्तेमाल करते हैं।
यही ठीक-ठीक वजह है कि arrow functions को अक्सर methods के अंदर callbacks के लिए इस्तेमाल किया जाता है — वे outer this inherit करते हैं, callback कहीं और invoke होने पर उसे खोने के बजाय।
उदाहरण: this in Arrow Functions
const user = {
name: "Sam",
greet() {
setTimeout(() => console.log(this.name), 0); // arrow inherits this
},
};
user.greet();
Classes के साथ this
किसी class method में, this आमतौर पर current object instance को refer करता है।
यही वजह है कि arrow functions खुद object methods के लिए कमज़ोर विकल्प हैं: चूंकि वे अपना खुद का this bind नहीं करते, वे instance के बजाय class body के surrounding scope से this inherit करेंगे।
उदाहरण: this With Classes
class User {
constructor(name) { this.name = name; }
greet() { console.log(this.name); } // this === instance
}
new User("Amit").greet();
Practice
this इस्तेमाल करते समय, पहले जांचें कि function को कैसे कॉल किया गया। यह आमतौर पर बता देता है कि this किसे refer करता है।
अगर किसी function की this value गलत लगे, तो call/apply/bind इसे explicitly override कर सकते हैं, जो अक्सर यह पुष्टि करने का सबसे तेज़ तरीका है कि असल में क्या हो रहा है।
उदाहरण: Practice
const user = { name: "Sam" };
function show() { console.log(this.name); }
show.call(user); // confirms this === user
- किसी object method को callback की तरह pass करना, जैसे
setTimeout(obj.show, 100), इसलिएthisखो जाता है और अबobjनहीं रहता। - किसी object method की तरह arrow function इस्तेमाल करना, जहाँ
thisउस object को point नहीं करता। - strict mode में किसी regular function में
thisइस्तेमाल करना, जहाँ यहundefinedहोता है, इसलिएthis.nameTypeErrorthrow करता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: