cover-img

What’s __proto in JavaScript Objects? What is Prototype?

20 January, 2023

1

1

0

Using Prototype in JavaScript

In JavaScript, a prototype is an object used as a template for creating new objects. Every JavaScript object has a prototype, an object from which it inherits properties and methods.

When you try to access a property or method of an object, and it does not exist, JavaScript will look for it in the object's prototype. This process is called "prototype chain" or "delegation" and allows for a kind of inheritance in JavaScript.

You can also create your prototype objects and use them as a template to create new objects. For example:

let prototype = {
sayHello: function() {
console.log("Hello");
}
};

let object = Object.create(prototype);
object.sayHello(); // "Hello"

Here, the object is created using the Object.create() method, which creates a new object and sets its prototype to the object passed as an argument.

The __proto__ Property

In JavaScript, the __proto__ property is a non-standard property used to access an object's prototype. It is considered as a non-standard way, and it is not recommended to use this property because it is not supported in all JavaScript environments.

Each object in JavaScript has a __proto__ property that references the object's prototype. This property is used to implement the prototype chain, which allows for a kind of inheritance in JavaScript. When you try to access a property or method of an object, and it does not exist, JavaScript will look for it in the object's __proto__, and so on, up the prototype chain until it finds it or reaches the end of the chain.

For example:

let prototype = {
sayHello: function() {
console.log("Hello");
}
};

let object = Object.create(prototype);
console.log(object.__proto__ === prototype); // true

It's worth noting that while __proto__ is supported in most modern browsers, it is not part of the ECMAScript standard, and it's not recommended to use it in production code. Instead, you can use the standard Object.getPrototypeOf() method to access an object's prototype or the Object.create() method to create a new object with a specific prototype.

1

1

0

ShowwcaseHQ

San Francisco, CA, USA

Showwcase is where developers hang out and find new opportunities together as a community

More Articles