A private member is a class field or method marked with #. Only code running within the class scope can access it, providing direct encapsulation rather than merely hiding a property by convention. section 2.3
Transaction fee state
A Transaction class can keep #feePercent private and calculate netTotal through a private static #precisionRound helper. External access such as tx.#feePercent throws a SyntaxError, while class methods retain access. section 2.3
Private members matter because they provide:
- Encapsulation for state that outside callers should not modify directly. section 2.3
- Private static helpers shared by instances without leaking into the public interface. section 2.3
- A class-based alternative to using modules and closures to emulate private state and privileged methods. section 2.3
Listing 2.8 Transaction and HashTransaction objects defined using classes
class Transaction {
sender = ''; #1
recipient = ''; #1
funds = 0.0;
#feePercent = 0.6; #2
constructor(sender, recipient, funds = 0.0) {
this.sender = sender;
this.recipient = recipient;
this.funds = Number(funds);
}
displayTransaction() {
return `Transaction from ${this.sender} to ${this.recipient}
for ${this.funds}`;
}
get netTotal() {
return Transaction.#precisionRound(this.funds * this.#feePercent, 2);
}
static #precisionRound(number, precision) { #2
const factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
}
class HashTransaction extends Transaction { #3
transactionId;
constructor(sender, recipient, funds = 0.0) {
super(sender, recipient, funds); #4
this.transactionId = this.calculateHash();
}
calculateHash() {
const data = [
this.sender,
this.recipient,
this.funds
].join('');
let hash = 0, i = 0;
while (i < data.length) {
hash = ((hash << 5) - hash + data.charCodeAt(i++)) << 0;
}
return hash**2;
}
displayTransaction() {
return `${this.transactionId}: ${super.displayTransaction()}`;
}
}
const tx = new HashTransaction('luis@tjoj.com', 'luke@tjoj.com', 10);
tx.displayTransaction();
// Prints:
// 64284210552842720: Transaction from luis@tjoj.com to luke@tjoj.com for 10
Inspect the Transaction and HashTransaction definitions to see private fields, a private static method, and inheritance used together. section 2.3











