In JavaScript, prototypes and prototype chains are important concepts for understanding objects and inheritance mechanisms. This article will introduce prototypes and prototype chains in JavaScript in detail, and explain this concept through sample code.
1. Prototype
In JavaScript, every object has a prototype. A prototype is an object that contains properties and methods that can be shared. When we access a property or method of an object, if the object itself does not define this property or method, the JavaScript engine will search up the prototype chain until it finds the corresponding property or method.
We can use Object.create()
methods to create a new object with a specified prototype. For example, the following code creates a Person
new object with prototype person1
:
const Person = {
greet: function() {
console.