Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Class-Based vs Prototype-Based OOP | Advanced Class Features
JavaScript Classes and OOP Foundations

bookClass-Based vs Prototype-Based OOP

メニューを表示するにはスワイプしてください

When you create objects in JavaScript, you can use either class-based or prototype-based object-oriented programming (OOP) approaches. Both methods ultimately allow you to define reusable blueprints for objects, but they differ in syntax and how you think about object creation.

In class-based OOP, which is familiar from many other languages and introduced in JavaScript with ES6, you define a blueprint with the class keyword. This approach uses clear, readable syntax for constructing objects and defining their behavior.

In prototype-based OOP, which is JavaScript's original model, you create objects that inherit directly from other objects. You define constructor functions and attach shared methods to their prototype. This approach is more flexible but can be less intuitive for those coming from class-based languages.

Here is a side-by-side comparison of the two approaches:

  • Class-based OOP:

    • Uses the class keyword;
    • Methods are defined inside the class body;
    • Inheritance uses the extends keyword;
    • Syntax is more declarative and familiar to developers from other OOP languages.
  • Prototype-based OOP:

    • Uses constructor functions and the prototype property;
    • Methods are attached to the constructor's prototype;
    • Inheritance is achieved by manipulating the prototype chain;
    • Syntax is more manual and flexible, but less structured.

Despite these differences, both approaches ultimately create objects that share methods and properties through prototypes under the hood.

1234567891011121314151617181920212223
// Prototype-based approach function Animal(name) { this.name = name; } Animal.prototype.speak = function () { return this.name + " makes a noise."; }; const dog1 = new Animal("Rex"); console.log(dog1.speak()); // Rex makes a noise. // Class-based approach class AnimalClass { constructor(name) { this.name = name; } speak() { return this.name + " makes a noise."; } } const dog2 = new AnimalClass("Buddy"); console.log(dog2.speak()); // Buddy makes a noise.
copy
question mark

Which statement best describes the main difference between class-based and prototype-based OOP in JavaScript?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt