function func(){}
alert(func.prototype);//[object Object]
alert(func.__proto__);//function (){[native code]}
b=new func;
alert(b.__proto__);//[object Object]
func.prototype=Array;//继承后
alert(b.__proto__);//[object Object]
alert(func.prototype);//function Array(){[native code]}
alert(func.__proto__);//function (){[native code]}
a=new Array;
alert(a.__proto__);//空,为什么不是[object Object]???
alert(Array.prototype);//空,为什么不是function Object(){[native code]}???
Array.prototype=new Object;//继承后
alert(Array.prototype);//空??为什么???
Array或其他引用类型怎么继承Object的所有属性和方法???
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
先回答简单的问题,
alert显示的是一个对象toString()之后的返回值。你看,下面,只要调用的是同一个toString他们的输出是相同的。另外,想看对象结构的话不要用alert,可以console中的函数。
Array.prototype应该是叫做“数组的原型”。在 JS 中所有使用new创建的对象,都会生成一个以这个函数为原型的对象,比如arr = new Array。表现就是arr.__proto__ === Array.prototype。只是new Object,new Array,new Function, new RegExp等都有其他的写法。当访问一个对象的属性,比如
arr.toString,其实访问的是arr.toString? arr._proto_.toString? arr._proto_._proto_.toString?....(按照这个顺序查找到的第一个)。又因为arr.__proto__ === Array.prototype,而Array.prototype具有toString,所以arr.toString访问的就是这里定义的那个函数,这样就实现了继承。在浏览器里最初的这种关系的设定是(黄色的箭头),Array的地位其实和下图中的Fish是一样的,只是Array,Array.prototype内置了一些属性和方法:

P.S.:
_proto_这个属性在标准和书里面叫做[[prototype]]所有对象默认都已经继承了
Object的属性和方法。不要用
alert,空数组用alert显示不出来。在控制台输入代码查看结果。Array.prototype是原生的对象模型,若你想在原生对象的基础上扩展,就要使用到它
比如对数组增加contains方法:
通过原型链继承的。
这个需要看看数组原型和继承链。
然后自己多试试就理解了。
Array.prototype指的是原生对象的原型,所有的引用类型都默认继承了Object,这个继承是通过原型链实现的,默认原型都包含一个内部指针指向Object.prototype,会继承toString(),valueOf()等方法。