JavaScript में OOP में संदर्भ की हानि

कक्षाओं के साथ काम करते समय, संदर्भ खो सकता है और this वर्ग की वस्तु पर इंगित नहीं करेगा, बल्कि किसी और चीज़ पर इंगित करेगा। आइए देखें कि यह कैसे हो सकता है और इसके साथ क्या करना चाहिए।

मान लीजिए कि हमारे पास एक वर्ग User है, जिसमें उपयोगकर्ता का नाम और शहरों की एक सूची है जहां यह उपयोगकर्ता रहा है:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
}

मान लीजिए कि एक विधि है जो शहरों को प्रदर्शित करती है:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(function(city) {
      console.log(city);
    });
  }
}

मान लीजिए कि इस विधि में हमने वर्ग की कुछ सहायक विधि का उपयोग करने का निर्णय लिया। इस स्थिति में, संदर्भ खो जाएगा:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(function(city) {
      console.log(this.#cape(city)); // संदर्भ खो गया
    });
  }
  
  #cape(str) {
    return str[0].toUpperCase() + str.slice(1);
  }
}

समस्या को ठीक किया जा सकता है, उदाहरण के लिए, एक तीर फ़ंक्शन का परिचय देकर:

javascriptclass User {
  constructor(name, cities) {
    this.name = name;
    this.cities = cities;
  }
  
  showCities() {
    this.cities.forEach(city => {
      console.log(this.#cape(city));
    });
  }
  
  #cape(str) {
    return str[0].toUpperCase() + str.slice(1);
  }
}
Задание 1

निम्नलिखित कोड में की गई त्रुटि को सही करें:

javascriptclass Employee {
  constructor(name, salary, coeffs) {
    this.name = name;
    this.salary = salary;
    this.coeffs = coeffs;
  }
  
  getTotal() {
    return this.coeffs.reduce(function(res, coeff) {
      return res + this.salary * coeff;
    }, 0);
  }
}

let employee = new Employee('john', 1000, [1.1, 1.2, 1.3]);
let total = employee.getTotal();
console.log(total);