Classes and Prototypes
Understand JavaScript's prototype model and use classes when instances share behavior.
JavaScript objects inherit behavior through prototype chains. Class syntax is a clearer way to define constructors and shared prototype methods.
Define an instance contract
course.js
class Course {
#completed = 0;
constructor(title, lessonCount) {
this.title = title;
this.lessonCount = lessonCount;
}
completeLesson() { this.#completed += 1; }
get progress() { return this.#completed / this.lessonCount; }
}
const html = new Course("HTML", 14);
Methods are shared through Course.prototype. Private fields are inaccessible outside the class body.
Composition before inheritance
Inheritance with extends can model a true subtype, but deep class trees couple behavior tightly. Small functions and composed objects are often easier to test.
composition.js
const withProgress = (lessonCount) => ({ completed: 0, lessonCount });
const course = { title: "CSS", progress: withProgress(18) };
Keep this
Know that classes use prototypes, keep instance state intentional, and prefer composition unless inheritance expresses a real relationship.
学习位置已保存在此设备上。