Skip to content

Commit 7d95659

Browse files
author
QP
committed
updated Examples in 'Objects and Data Structures'
1 parent b7c1c8a commit 7d95659

File tree

1 file changed

+25
-28
lines changed

1 file changed

+25
-28
lines changed

README.md

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -943,48 +943,45 @@ cần phải tìm kiếm và thay đổi mỗi accessor trong codebase của b
943943

944944
**Không tốt:**
945945
```javascript
946-
class BankAccount {
947-
constructor() {
948-
this.balance = 1000;
949-
}
950-
}
946+
function makeBankAccount() {
947+
// ...
951948

952-
const bankAccount = new BankAccount();
949+
return {
950+
balance: 0,
951+
// ...
952+
};
953+
}
953954

954-
// Buy shoes...
955-
bankAccount.balance -= 100;
955+
const account = makeBankAccount();
956+
account.balance = 100;
956957
```
957958

958959
**Tốt:**
959960
```javascript
960-
class BankAccount {
961-
constructor(balance = 1000) {
962-
this._balance = balance;
963-
}
961+
function makeBankAccount() {
962+
// this one is private
963+
let balance = 0;
964964

965-
// Không cần phải thêm tiền tố `get` hay `set` để trở thành một getter hay setter
966-
set balance(amount) {
967-
if (this.verifyIfAmountCanBeSetted(amount)) {
968-
this._balance = amount;
969-
}
965+
// Một "getter", thiết lập public thông qua đối tượng được trả về dưới đây
966+
function getBalance() {
967+
return balance;
970968
}
971969

972-
get balance() {
973-
return this._balance;
970+
// Một "setter", thiết lập public thông qua đối tượng được trả về dưới đây
971+
function setBalance(amount) {
972+
// ... validate before updating the balance
973+
balance = amount;
974974
}
975975

976-
verifyIfAmountCanBeSetted(val) {
976+
return {
977977
// ...
978-
}
978+
getBalance,
979+
setBalance,
980+
};
979981
}
980982

981-
const bankAccount = new BankAccount();
982-
983-
// Buy shoes...
984-
bankAccount.balance -= shoesPrice;
985-
986-
// Get balance
987-
let balance = bankAccount.balance;
983+
const account = makeBankAccount();
984+
account.setBalance(100);
988985

989986
```
990987
**[⬆ về đầu trang](#mục-lục)**

0 commit comments

Comments
 (0)