In JavaScript, both
`prototype` and
`__proto__` (often accessed using the `Object.getPrototypeOf()` and `Object.setPrototypeOf()` methods) are related to the prototype chain and object
inheritance, but they have different roles and purposes.
1. `prototype`:
The `prototype` property is a property of a constructor function, such as `function Person() {}`, and is used to define and store properties and methods that will be inherited by objects created using that constructor function. It is an
object that serves as a blueprint for creating other objects. When you create an instance of a constructor function using the `new` keyword, the newly created object's `__proto__` property is set to the `prototype` property of the constructor function.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}.`);
};
const person = new Person('Alice');
person.greet(); // Hello, my name is Alice.
In this example, `Person.prototype` is the prototype
object associated with the `Person` constructor function. The `greet()` method defined on `Person.prototype` is then inherited by objects created with `new Person()`.
2. `__proto__`:
The `__proto__` property is a property of individual objects that references the prototype of the object. It is a reference to the object's internal [[Prototype]] property. It allows objects to access properties and methods defined on their prototype.
Example:
const person = { name: 'Alice' };
console.log(person.__proto__ === Object.prototype); // true
person.toString(); // inherited from Object.prototype
In this example, `Object.prototype` is the prototype object for all objects created in JavaScript, including `person`. The `__proto__` property of `person` references `Object.prototype`, allowing `person` to access methods like `toString()` defined on `Object.prototype`.
It's important to note that while `__proto__` is a non-standard property, it is widely supported in browsers. It has been standardized as `[[Prototype]]` in the ECMAScript specification, and you should prefer using the `Object.getPrototypeOf()` and `Object.setPrototypeOf()` methods to access and set the prototype of an object.
In summary,
`prototype` is a property of a constructor function used to define properties and methods that will be inherited by instances created with that constructor, while
`__proto__` is a property of individual objects that references their prototype in the prototype chain.