Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Student = (function () {
- function Student(name, age, scores) {
- Person.call(this, name);
- this.age = age;
- this.scores = scores;
- }
- Student.inherits(Person);
- Object.defineProperties(Student.prototype, {
- age: {
- get: function() { return this._age; },
- set: function(value) {
- value.checkIsPositive(); // validation
- this._age = value;
- }
- },
- scores: {
- get: function() { return this._scores; },
- set: function(value) {
- // validation here
- this._scores = value;
- }
- },
- toString: {
- value: function () {
- return "Student " + this.name + " is " + this.age + " years old.";
- }
- }
- });
- return Student;
- }());
- По този начин можем да ползваме пропъртитата подобно на C#:
- var pesho = new Student();
- pesho.name = 'Pesho Peshev';
- pesho.age = 30;
- console.log(pesho.name); // Pesho Peshev
- console.log(pesho.toString()); // Student Pesho Peshev is 30 years old.
- "Закачам" методите и пропъртитата към прототипа с Object.defineProperties така не губя наследните методи и пропъртита и спестявам многократното повтаряне на Student.prototype :)
- Този синтаксис се поддържа във всички нормални броузери и IE9+ (работи и в Node.JS)
Advertisement
Add Comment
Please, Sign In to add comment