乐闻世界logo
搜索文章和话题

What is the Difference Between `prototype` and `__proto__` in JavaScript?

2024年8月9日 17:42

In JavaScript, the prototype property and the __proto__ property (often read as "proto") are key concepts related to the object prototype chain, but they differ in usage and purpose.

prototype Property

prototype is a property of function objects. When you create a new object using a constructor function, the internal [[Prototype]] (which is its __proto__ property) is set to the prototype property of the constructor function. This means that all objects created with the same constructor share the same prototype object.

For example, if we have a constructor function:

javascript
function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log(`Hello, my name is ${this.name}`); };

When we create a Person instance:

javascript
var person1 = new Person("Alice");

person1 object's [[Prototype]] (i.e., __proto__) points to Person.prototype, allowing person1 to access the sayHello method.

__proto__ Property

__proto__ is an internal property possessed by every JavaScript object, pointing to the prototype of the object. It serves as a link from the object to the prototype property of its constructor function. According to the ECMAScript standard, __proto__ is the implementation of [[Prototype]], which is an internal property of the object. In modern JavaScript development, it is generally recommended to use Object.getPrototypeOf(obj) to retrieve an object's prototype instead of directly using __proto__, as __proto__ is not supported in all JavaScript environments.

Again, using the previous example, person1.__proto__ points to Person.prototype because person1 is created by the Person constructor function.

Summary

  • prototype is a property specific to functions, used to define the prototype for instance objects when the function is used as a constructor.
  • __proto__ is a property possessed by every object, pointing to its prototype.

In practice, prototype is used to implement prototypal inheritance and share properties and methods, while __proto__ provides a way to access and manipulate the object's prototype chain. However, directly manipulating __proto__ is considered an unsafe practice, especially in modern JavaScript programming, where it is recommended to use methods like Object.getPrototypeOf() and Object.setPrototypeOf() instead of directly using __proto__.

标签:前端