深入理解 JavaScript 原型链:Object、Function 与 Array 的关系

作者:纸飞机

时间:2026-10-26

浏览:315

本文深入解析 JavaScript 的原型继承机制,重点阐述 Object.prototype 作为所有对象根节点的作用,以及 Function.prototype 与 Object.prototype 的继承关系。通过代码示例说明修改内置构造函数原型对 Object、Array 等类型的影响,并区分函数对象与实例对象在原型链查找上的差异,帮助开发者理解原型链的核心原理。

文章目录

Object.prototype 的基础地位

Object.prototype


JavaScript 语言的设计基于原型继承模型,其中每个对象都拥有一个 prototype 属性。Object.prototype 被视为所有对象的最终根节点,且该属性本身不可被修改或覆盖。


代码如下:

 
Object.prototype=null;
alert(Object.prototype);//[object Object]

Object 构造函数与原型的关系

Object 与 Object.prototype


Object 构造函数继承自 Object.prototype。当向 Object.prototype 添加属性或方法时,这些更改会立即反映在 Object 构造函数本身。例如:


代码如下:

 
Object.prototype.nameStr="Object Prototype";
Object.prototype.getName=function(){return this.nameStr};
alert(Object.getName());//Object Prototype

Function.prototype 的继承特性

Function.prototype 与 Object.prototype


由于 Object.prototype 是所有对象的根基,Function.prototype 同样继承自 Object.prototype,因此它拥有 Object.prototype 的所有属性和方法。例如:


代码如下:

 
Object.prototype.nameStr="Object Prototype";
Object.prototype.getName=function(){return this.nameStr};
alert(Function.prototype.getName());//Object Prototype


内置构造函数对 Function.prototype 的响应

Object/Function/String/Number/Boolean/Array 与 Date


Object、Function、String、Number、Boolean、Array 和 Date 本质上都是函数。由于函数都继承自 Function.prototype,因此修改 Function.prototype 同样会影响上述所有内置构造函数。例如:


代码如下:

 
Function.prototype.initType='Function Type';
Function.prototype.getType=function(){return this.initType};
//alert(Object.getType());//Function Type
//alert(Date.getType());//Function Type
//alert(Number.getType());//Function Type
//alert(String.getType());//Function Type
//alert(Boolean.getType());//Function Type
alert(Array.getType());//Function Type

同样,Function.prototype 会将来自 Object.prototype 的影响传递给其下一级。例如:


代码如下:

 
Object.prototype.nameStr="Object Prototype";
Object.prototype.getName=function(){return this.nameStr};
alert(Function.prototype.getName());//Object Prototype
alert(Array.getName());//Object Prototype

代码如下:

 
alert(Boolean.prototype.getName());//Object Prototype
Array 及其原型链的复杂性Array/Array.prototype 与 Function.prototype/Object.prototype

Array 是一个函数对象,因此受 Function.prototype 的影响;而 Array.prototype 不是函数对象,不受 Function.prototype 影响,但作为对象,它受 Object.prototype 的影响。例如:


代码如下:

 
Object.prototype.nameStr="Object Prototype";
Object.prototype.getName=function(){return this.nameStr};
//alert(Function.prototype.getName());//Object Prototype
//alert(Boolean.prototype.getName());//Object Prototype
Function.prototype.initFun=function(){
return 'Function.prototype.initFun';
} 
alert(Array.initFun());//Function.prototype.initFun
var arr=['a','b'];
alert(arr.getName());//Object Prototype
alert(arr.initFun());//Error: arr.initFun is not a function
alert(arr.initFun);//undefined

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章