No announcement
 

Prototypes & Prototypal Inheritance, ES6+ Classes

Prototypes and Prototypal Inheritance

In JavaScript, every object has a prototype, which is another object it inherits properties and methods from. Prototypal inheritance allows objects to inherit properties and behaviors from their prototypes, creating a chain of prototypes.

Example:

pp_inheritnace.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Prototypes and Prototypal Inheritance Example</title>
</head>
<body>

<h2>JavaScript Prototypes and Prototypal Inheritance:</h2>
<script>
// Prototype
let personPrototype = {
  greet: function() {
    console.log("Hello, I'm " + this.name + ".");
  }
};

// Object with prototypal inheritance
let person1 = Object.create(personPrototype);
person1.name = "Alice";

let person2 = Object.create(personPrototype);
person2.name = "Bob";

person1.greet(); // Output: Hello, I'm Alice.
person2.greet(); // Output: Hello, I'm Bob.
</script>

</body>
</html>

Output
Hello, I'm Alice. Hello, I'm Bob.

In this example, we created a personPrototype object with a greet method. Then, we created two new objects person1 and person2 using Object.create(), which allows these objects to inherit from personPrototype. Both person1 and person2 have their own name property and can access the greet method through prototypal inheritance.

ES6+ Classes

ES6 introduced a new way to create objects and handle inheritance using the class syntax. Classes in JavaScript are syntactical sugar over prototype-based inheritance.

Example:

es6.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript ES6+ Classes Example</title>
</head>
<body>

<h2>JavaScript ES6+ Classes:</h2>
<script>
// Class
class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log("Hello, I'm " + this.name + ".");
  }
}

// Object with class
let person1 = new Person("Alice");
let person2 = new Person("Bob");

person1.greet(); // Output: Hello, I'm Alice.
person2.greet(); // Output: Hello, I'm Bob.
</script>

</body>
</html>

Output
Hello, I'm Alice. Hello, I'm Bob.

In this example, we created a Person class with a constructor and a greet method. We used the new keyword to create two instances of the Person class: person1 and person2. Each instance has its own name property and can access the greet method.

ES6+ classes provide a more familiar syntax for developers coming from other programming languages and make it easier to work with object-oriented programming concepts in JavaScript.

Both prototypes and classes are used to implement inheritance and object creation in JavaScript. While prototypes are the foundation of JavaScript's prototypal inheritance, classes offer a more structured and familiar way to define objects and handle inheritance in modern JavaScript.