|
| 1 | +console.log('Getters and setters'); |
| 2 | + |
| 3 | +function Circle(radius) { |
| 4 | + this.radius = radius; |
| 5 | + let start = { x: 0, y: 0 }; |
| 6 | + let compute = function (factor) { |
| 7 | + console.log('Factor: ', factor); |
| 8 | + }; |
| 9 | + this.draw = function () { |
| 10 | + compute(0.1); |
| 11 | + console.log('draw'); |
| 12 | + }; |
| 13 | + this.getStart = function () { |
| 14 | + return start; |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +const c = new Circle(2); |
| 19 | +c.draw(); |
| 20 | +console.log(c.getStart(), '\n'); |
| 21 | + |
| 22 | +function CircleB(radius) { |
| 23 | + this.radius = radius; |
| 24 | + let start = { x: 0, y: 0 }; |
| 25 | + this.draw = function () { |
| 26 | + console.log('draw'); |
| 27 | + }; |
| 28 | + Object.defineProperty(this, 'start', { |
| 29 | + get: function () { |
| 30 | + return start; |
| 31 | + }, |
| 32 | + }); |
| 33 | +} |
| 34 | + |
| 35 | +const cb = new CircleB(2); |
| 36 | +cb.draw(); |
| 37 | +console.log('Object.defineProperty -> get \n', cb.start, '\n'); |
| 38 | + |
| 39 | +function CircleC(radius) { |
| 40 | + this.radius = radius; |
| 41 | + let start = { x: 0, y: 0 }; |
| 42 | + this.draw = function () { |
| 43 | + console.log('draw'); |
| 44 | + }; |
| 45 | + Object.defineProperty(this, 'start', { |
| 46 | + get: function () { |
| 47 | + return start; |
| 48 | + }, |
| 49 | + set: function (value) { |
| 50 | + if (!value.x && !value.y) throw new Error('Invalid location'); |
| 51 | + start: value; |
| 52 | + }, |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +const cc = new CircleC(2); |
| 57 | +cc.draw(); |
| 58 | +console.log('Object.defineProperty -> get / set \n', cc.start, '\n'); |
| 59 | +// cc.start = 3; // reports an error |
| 60 | +cc.start.x = 5; |
| 61 | +cc.start.y = 3; |
| 62 | +console.log(cc.start); |
0 commit comments