JavaScript OOP හි සන්දර්භය අහිමි වීම
පන්ති සමඟ වැඩ කිරීමේදී සන්දර්භය
අහිමි විය හැකි අතර this
පන්ති වස්තුව වෙනුවට වෙනත් යමක්
වෙත යොමු වනු ඇත.
එය සිදුවිය හැකි ආකාරය සහ එයට
කළ හැකි දේ දෙස බලමු.
අපට User පන්තියක් ඇතැයි සිතමු,
එය පරිශීලකයාගේ නම සහ මෙම පරිශීලකයා
සිටින නගර අරාව
අඩංගු කරයි:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
}
නගර ප්රදර්ශනය කරන ක්රමයක් ඇතැයි සිතමු:
class User {
constructor(name, cities) {
this.name = name;
this.cities = cities;
}
showCities() {
this.cities.forEach(function(city) {
console.log(city);
});
}
}
මෙම ක්රමය තුළ අපි පන්තියේ යම් උපකාරක ක්රමයක් භාවිතා කිරීමට තීරණය කළේ යැයි සිතමු. මෙම අවස්ථාවේදී සන්දර්භය අහිමි වනු ඇත:
class 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);
}
}
ගැටළුව නිවැරදි කළ හැකිය, උදාහරණයක් ලෙස, ඊතල ශ්රිතයක් හඳුන්වා දීමෙන්:
class 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);
}
}
පහත කේතයේ සිදු කරන ලද දෝෂය නිවැරදි කරන්න:
class 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);