javascript - Array.prototype是什么?Array怎么继承Object的属性??

查看:129
本文介绍了javascript - Array.prototype是什么?Array怎么继承Object的属性??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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的所有属性和方法???

解决方案

先回答简单的问题,alert 显示的是一个对象toString()之后的返回值。你看,下面,只要调用的是同一个toString 他们的输出是相同的。
另外,想看对象结构的话不要用alert,可以console中的函数。

function func(){} // 这句不考虑函数名的话等价于 func = new Function()
alert(func.prototype);//[object Object]
//这个调用的其实是`Object.prototype.toString`(原因下面说)
alert(func.__proto__);//function (){[native code]}
//这个调用的其实是`Function.prototype.toString`(原因下面说)

b=new func;
alert(b.__proto__);//[object Object]
//这个调用的其实是`Object.prototype.toString`

func.prototype=Array;//继承后
alert(b.__proto__);//[object Object]
//这不是继承,`b.__proto__=func.prototype`这种赋值是再`b=new func`时发生的,后面改变`func.prototype`不影响`b.__proto__`
alert(func.prototype);//function Array(){[native code]}
//Array是一个函数,所以这个toString是Function.prototype.toString
alert(func.__proto__);//function (){[native code]}
//同上

a=new Array;
alert(a.__proto__);//空,为什么不是[object Object]???
//这个调用的是`Array.prototype.toString`,可是this是Array.prototype,Array.prototype.toString是将数组转换成字符串,Array.prototype不是数组,所以返回空字符串(根据Array.prototype.toString的定义)
//http://zonxin.github.io/post/2015/07/javascript-array-prototype

 alert(Array.prototype);//空,为什么不是function Object(){[native code]}???
//同上

 Array.prototype=new Object;//继承后
 alert(Array.prototype);//空??为什么???
//Array.prototype是只读的,所以上面的赋值没什么卵用

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]]

这篇关于javascript - Array.prototype是什么?Array怎么继承Object的属性??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆