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);