Venciity

JS OOP

Mar 25th, 2015
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var Student = (function () {
  2.     function Student(name, age, scores) {
  3.         Person.call(this, name);
  4.         this.age = age;
  5.         this.scores = scores;
  6.     }
  7.  
  8.     Student.inherits(Person);
  9.  
  10.     Object.defineProperties(Student.prototype, {
  11.         age: {
  12.             get: function() { return this._age; },
  13.             set: function(value) {
  14.                 value.checkIsPositive(); // validation
  15.                 this._age = value;
  16.             }
  17.         },
  18.         scores: {
  19.             get: function() { return this._scores; },
  20.             set: function(value) {
  21.                 // validation here
  22.                 this._scores = value;
  23.             }
  24.         },
  25.         toString: {
  26.             value: function () {
  27.                 return "Student " + this.name + " is " + this.age + " years old.";
  28.             }
  29.         }
  30.     });
  31.  
  32.     return Student;
  33. }());
  34.  
  35. По този начин можем да ползваме пропъртитата подобно на C#:
  36.  
  37. var pesho = new Student();
  38. pesho.name = 'Pesho Peshev';
  39. pesho.age = 30;
  40.  
  41. console.log(pesho.name); // Pesho Peshev
  42. console.log(pesho.toString()); // Student Pesho Peshev is 30 years old.
  43.  
  44. "Закачам" методите и пропъртитата към прототипа с Object.defineProperties така не губя наследните методи и пропъртита и спестявам многократното повтаряне на Student.prototype :)
  45. Този синтаксис се поддържа във всички нормални броузери и IE9+ (работи и в Node.JS)
Advertisement
Add Comment
Please, Sign In to add comment