Skip to content

Commit fea883d

Browse files
committed
gettres and setters - Object.defineProperty
1 parent 63f9a7b commit fea883d

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

src/02-oop/17-getters-setters.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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);

src/02-oop/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@ const runFile11 = './11-fn-are-objects';
88
const runFile13 = './13-object-properties';
99
const runFile14 = './14-enumerating-properties';
1010
const runFile16 = './16-private-properties-methods';
11+
const runFile17 = './17-getters-setters';
1112

12-
require(runFile16);
13+
require(runFile17);

0 commit comments

Comments
 (0)