জাভাস্ক্রিপ্টে 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);