5 min read
ā¢Question 9 of 50hardWhat are Prototypes in JavaScript?
Understanding prototypal inheritance.
What You'll Learn
- What prototypes are
- Prototype chain
- Prototypal inheritance
What is a Prototype?
Every JavaScript object has an internal link to another object called its prototype. Objects inherit properties and methods from their prototype.
Prototype Chain
code.jsJavaScript
const arr = [1, 2, 3];
// arr ā Array.prototype ā Object.prototype ā null
console.log(arr.__proto__ === Array.prototype); // true
console.log(Array.prototype.__proto__ === Object.prototype); // trueCreating Objects with Prototypes
code.jsJavaScript
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound');
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(this.name + ' barks');
};
const dog = new Dog('Rex');
dog.speak(); // 'Rex makes a sound'
dog.bark(); // 'Rex barks'Modern Class Syntax
code.jsJavaScript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a sound');
}
}
class Dog extends Animal {
bark() {
console.log(this.name + ' barks');
}
}