Site icon Kaizen.Personal computer work.

Prototype chain(JavaScript)

Japanese version.

The prototype chain in JavaScript is the mechanism by which object properties are accessed, where if a property does not exist on an object, the search moves up to the object's prototype (parent object) and continues up the chain until the property is found or until the top of the chain is reached, at which point undefined is returned.

Specifically, when an object property is accessed, the search begins with the object itself, and if the property does not exist, the search continues up the prototype chain to the object's prototype object. If the property is still not found, the search continues up the chain until the top level Object prototype is reached. This prototype chain is a fundamental feature of JavaScript's object-oriented programming, and is used to implement concepts such as inheritance and polymorphism. In JavaScript, all objects inherit from the Object object, so all objects can use properties defined on the Object prototype.

Understanding the prototype chain is important when constructing objects, and is also important when inheriting from objects or creating custom objects.

In JavaScript, every object has a prototype, which is used to inherit properties from other objects. JavaScript has a mechanism called the prototype chain, which allows you to traverse an object's prototype chain to search for its properties.

For example, let's say we have an object like this:

let person = {name: "John"};

This object has a property called name. However, if we change the prototype of the person object like this:

let person = {name: "John"};
let anotherPerson = {age: 25};
person.__proto__ = anotherPerson;

console.log(person.name);
console.log(anotherPerson.name);
console.log(person.age);
console.log(anotherPerson.age);

Now, the person object inherits the properties of the anotherPerson object. When searching for the name property on the person object, JavaScript first checks if the property exists on the person object itself, and if it doesn't, it traverses the prototype chain of the person object to search for the age property on the anotherPerson object. This way, the prototype chain allows us to express the inheritance relationship between objects.

Links

JavaScript Articles

JavaScript
Exit mobile version