Advertisement
stoyanmkd

JS - Closure Encapsulation

Feb 8th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var school = (function() {
  2.     var students = [];
  3.     var teachers = [];
  4.  
  5.     function addStudent(name, grade) {
  6.         students.push({
  7.             name : name,
  8.             grade : grade
  9.         });
  10.  
  11.     }
  12.     function addTeacher(name, speciality) {
  13.         teachers.push({
  14.             name : name,
  15.             speciality : speciality
  16.         });
  17.  
  18.     }
  19.     function getTeachers(speciality) {
  20.         return teachers.filter(function(t){
  21.             return t.speciality === speciality
  22.         });
  23.     }
  24.     function getStudents(grade) {
  25.         return students.filter(function(s){
  26.             return s.grade === grade
  27.         });
  28.     }
  29.  
  30.     return {
  31.         as: addStudent,
  32.         at: addTeacher,
  33.         gs: getStudents,
  34.         gt: getTeachers
  35.     };
  36. })();
  37.  
  38. school.as("ivan", 5);
  39. school.as("ivanka", 6);
  40.  
  41. school.at("gogo", "maths");
  42. school.at("gergana", "maths");
  43.  
  44. console.log(school.gs(5));
  45. console.log(school.gt("maths"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement