详细介绍 JavaScript 中的 Proto 与 Prototype
在 JavaScript 中,我们说一切都是对象。在本文中,你将更深入地了解 JavaScript 中的 __proto__
和 prototype
是什么,以及为什么一切都是对象
这句话成立。
每当你在 JavaScript 中创建数组、对象和函数时,你可能知道你可以访问所有可用的预定义方法。
你有没有想过我们如何获得所有这些方法?
这个问题的答案是因为 JavaScript 自动将 __proto__
附加到包含所有这些属性和方法的数组、对象或函数。
__proto__
只是一个对象。无论你是创建数组、对象还是函数,都将为你提供对这些特定方法的访问。
让我们举个例子来理解 __proto__
。
在这里,我们创建了一个数字数组 arr
。如果你在 arr
上控制台 _proto__
,你会看到它将列出数组提供的所有属性。
例如,它将提供对其构造函数和所有数组方法(如 push、pop、map、forEach 等)的访问权限。
var arr = [1,2,3];
console.log(arr.__proto__)
输出:
这不仅适用于数组。无论你在 JavaScript 中创建什么,都会附加一个 __proto__
对象。
所有这些存在于 __proto__
中的属性都可以使用点运算符轻松访问。
现在我们了解了 __proto__
对象,现在让我们看看 JavaScript 中的 prototype
是什么。
为此,我们举个例子。
console.log(arr.__proto__);
console.log(Array.prototype);
输出:
假设你打印我们创建的 arr
的 __proto__
和 Array
类的 prototype
。然后你会发现它们都是一样的,如上图所示。
这是因为每当我们创建一个数组时,它都会从数组类的原型中获取所有属性和方法,然后将其存储在你创建的数组的 __proto__
中。
简单来说,prototype
是类的属性,而 __proto__
是该类实例的属性。它们都是对象。
此外,如果你打印 arr.__proto__
的 __proto__
的输出,你会看到它与 Object
类的 prototype
相同。这说明如下。
console.log(arr.__proto__.__proto__);
console.log(Object.prototype);
输出:
在这里,究竟发生的是数组 arr._proto__
是数组类的原型。而 arr.__proto__.__proto__
是 Object
类原型。
这形成了一个链,所以这个概念在 JavaScript 中被称为原型链。
最后,你可以看到,即使我们创建了一个数组,它也存储了 Object
的引用。
这现在适用于数组,但也适用于我们创建的所有其他东西,比如 JavaScript 中的对象和函数。这就是为什么我们说 JavaScript 中的一切都是对象。
对象原型,即 arr.__proto__.__proto__.__proto__
只是 null
,这意味着它是链的末端。
console.log(arr.__proto__.__proto__.__proto__);
输出:
null
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。