Guest User

Untitled

a guest
Oct 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. // Объявление класса
  2. class Point {
  3. constructor(x, y) {
  4. this.x = x;
  5. this.y = y;
  6. }
  7.  
  8. toString() {
  9. return `(${this.x}, ${this.y})`;
  10. }
  11. }
  12.  
  13. // создание экземпляра
  14. let point = new Point(2, 1);
  15. console.log( point.toString() ); // (2, 1)
  16.  
  17.  
  18. /* ---------------------------------------------*/
  19.  
  20.  
  21. // Наследование
  22. class ColorPoint extends Point {
  23. constructor(x, y, color) {
  24. super(x, y);
  25. this.color = color;
  26. }
  27. toString() {
  28. return `${super.toString()} in ${this.color}`;
  29. }
  30. }
  31.  
  32. let colorPoint = new ColorPoint(4, 2, 'red');
  33. console.log( colorPoint.toString() ); // (4, 2) in red
  34.  
  35. console.log(colorPoint instanceof ColorPoint); // true
  36. console.log(colorPoint instanceof Point); // true
  37.  
  38.  
  39. /* ---------------------------------------------*/
  40.  
  41.  
  42. // Статические методы
  43. class Button {
  44. static getElementType() {
  45. return 'button';
  46. }
  47. constructor(name) {
  48. this.color = color;
  49. }
  50. click() {
  51. console.log('Button clicked!');
  52. }
  53. }
  54.  
  55. console.log( Button.getElementType() ); // button
  56.  
  57.  
  58. /* ---------------------------------------------*/
  59.  
  60.  
  61. // Геттеры и сеттеры
  62. class User {
  63. constructor(firstName, lastName) {
  64. this.firstName = firstName;
  65. this.lastName = lastName;
  66. }
  67.  
  68. // геттер
  69. get fullName() {
  70. return `${this.firstName} ${this.lastName}`;
  71. }
  72.  
  73. // сеттер
  74. set fullName(newValue) {
  75. [this.firstName, this.lastName] = newValue.split(' ');
  76. }
  77. };
  78.  
  79. let user = new User('Вася', 'Пупков');
  80. console.log( user.fullName ); // Вася Пупков
  81.  
  82. user.fullName = 'Иван Петров';
  83. console.log( user.fullName ); // Иван Петров
Add Comment
Please, Sign In to add comment