其实我也说不清他们之间的关系,或者说我也只能用代码推导出他们之间表层的关系,因为我也没有看过他们 底层的源码,网上关于源码级的分析我也暂时没有找到,所以以下内容我也只是给自己做个注释,便于自己理解,不喜勿喷。先来一张图
实例代码
console.log(typeof Object); //function
console.log(Object.constructor == Function); //true
console.log(Object.__proto__ == Function.prototype); //true
console.log(typeof Object.prototype);//object
console.log(typeof Array); //function
console.log(Array.constructor == Function); //true
console.log(Array.__proto__ == Function.prototype); //true
console.log(typeof Array.prototype);//object
console.log(typeof Function); //function
console.log(Function.constructor == Function); //true
console.log(Function.__proto__ == Function.prototype); //true
console.log(typeof Function.prototype);//function
console.log(Function.prototype.prototype);//undefined
JS里有很多内置函数如:alert、isNaN、parseInt等,也内置了一些构造函数如Object、Function、Array等, 我们知道JS中一切皆对象,所以函数也是对象,由打印得知内置函数对象的原型__proto__统一指向了Function构造函数的prototype对象,而且内置函数的constructor也指向了Function,我们可以得出结论内置构造函数都是Function的实例。其实所有的构造函数都是Function的实例(不包括Function.prototype函数,它比较特殊)。但我们发现一个现象Object.prototype、Array.prototype的类型是object对象,而Function.prototype是一个function函数,这一点需要注意,而且这个函数和其他的也不同,因为它也没有prototype属性,即Function.prototype.prototype为undefined,我们把Object.prototype称为原型链的根,而所有对象在原型链上查询的终点就是到Object.prototype.__proto为止,也就有了网上经常说的Function.prototype是Object的实例,其实是任何对象都是Object的实例。如:Array.prototype。
上面说了半天,好像也并没有说出它两个的区别,先来看下这个
console.log(Function instanceof Function); //true
console.log(Object instanceof Function); //true
console.log(Function instanceof Object); //true
console.log(Object instanceof Object); //true
console.log(Array instanceof Function); //true
console.log(Array instanceof Object); //true
我们在上边已经得出了结论:所有的函数都是Function的实例,任何对象都是Object的实例(函数也对象), 所以上边的打印都是true。
1:所有对象和函数 instanceof Object //true (因为JS万物皆对象,函数也是对象) 2:所有函数 instanceof Function //true (因为所有函数的都是Function的实例) 3:除Object和Function之外的构造函数 instanceof 自身 //false (因为构造函数的原型链上只有 Function.prototype和Object.prototype,而没有他们自身的prototype)
个人总结:
我认为在JS中万物起源于Function,通过Function创建了自己Function构造函数,然后又创建了Function.prototype函数(它比较特殊因为不是对象),并使Function.__proto__指向Function.prototype,紧接着又通过Function创建出了Object构造函数,也让Object.__proto__指向Function.prototype,然后又创建了Object.prototype对象,这时JS又把Object.prototype设置成了原型链的根,又让Function.prototype 函数对象的__proto__指向了Object.prototype对象,此时已经完成了初始化工作。