判斷[].__proto__.__proto__ === {}.__proto__結果並解釋為什麼[程式碼]

王铁柱6發表於2024-12-04

The statement [].__proto__.__proto__ === {}.__proto__ evaluates to true in most JavaScript environments. Here's why:

  • [].__proto__: This refers to the prototype of an array. The prototype of an array is the Array.prototype object. It provides methods like push(), pop(), map(), etc.

  • [].__proto__.__proto__: This refers to the prototype of the array's prototype. Array.prototype itself is an object, so its prototype is the base object prototype, which is Object.prototype.

  • {}.__proto__: This refers to the prototype of a plain object. The prototype of a plain object is also Object.prototype.

Therefore, since both [].__proto__.__proto__ and {}.__proto__ resolve to the same Object.prototype, the comparison returns true.

Important Note: Direct access to the __proto__ property is deprecated. While it might work in many environments, it's not universally supported and considered bad practice. The modern and preferred way to access the prototype is using Object.getPrototypeOf():

Object.getPrototypeOf(Array.prototype) === Object.getPrototypeOf({}) // true

This approach is more robust and standards-compliant. Using __proto__ is discouraged because it can lead to performance issues and compatibility problems across different JavaScript engines.

相關文章