-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-getters-e-setters.js
More file actions
89 lines (73 loc) · 2 KB
/
02-getters-e-setters.js
File metadata and controls
89 lines (73 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class Product {
constructor(name, price) {
this.name = name;
this._price = price;
}
get price() {
return this._price.toFixed(2);
}
set price(value) {
if (typeof value === 'number' && value > 0) {
this._price = value;
} else {
throw new Error('Valor errado');
}
}
describe() {
return `${this.name} custa R$ ${this.price}`;
}
};
let item;
try {
item = new Product('keyboard', 150)
item.price = -4;
console.log(item.price);
console.log(item.describe());
} catch (error) {
console.log('Vai dar um erro pois o valor passado a price é negativo e o set price faz uma verificação');
item || (item = new Product('keyboard', 150));
item.price = 200
console.log(item.price);
console.log(item.describe());
}
// Lembrando que class é apenas uma abstração para funções construtoras e prototypes:
function Product2(name, price) {
this.name = name;
this._price = price;
}
Object.defineProperty(Product2.prototype, 'price', {
get: function() {
return this._price.toFixed(2);
},
set: function(value) {
if (typeof value === 'number' && value > 0) {
this._price = value;
} else {
throw new Error('Valor errado');
}
}
});
Object.defineProperty(Product2.prototype, 'describe', {
value: function() {
return `${this.name} custa R$ ${this.price}`;
},
writable: false,
enumerable: true,
configurable: false
})
// ou
Product2.prototype.describe = function() {
return `${this.name} custa R$ ${this.price}`;
};
let item2;
try {
item2 = new Product2('keyboard', 150);
item2.price = -4;
console.log(item2.price);
} catch (error) {
console.log('Vai dar um erro pois o valor passado a price é negativo e o set price faz uma verificação');
item2 || (item2 = new Product2('keyboard', 150));
item2.price = 200;
console.log(item2.price);
console.log(item2.describe());
}