JavaScript里面有很多对象,但是引用方法不尽相同,带着好奇的心探索一番,原来对象主要分为3大类。
一、内置对象(Build-in Object)
1、创建
在引擎初始化阶段就被创建,不需要New,每个内置对象都是原生对象,内置对象是原生对象的子集。
2、有哪些
Global、Math、JSON。
实例化的目的就是想用实例化后的对象里的属性和方法,那么既然JSON和Math已经是对象了,就省去实例化的操作喽,无需new。
Math.__proto__ === Object.prototype // true Math.construrctor == Object // true JSON.__proto__ === Object.prototype // true JSON.construrctor == Object // true
二、原生对象(Native Object)
1、创建
原生对象包含一些在运行过程中动态创建的对象,要New。
2、有哪些
Object、Function、Array、String、Boolean、Number、Date、RegExp、Error。
3、对象原型
Function是对象函数,通过new Function()创建,所以Function.__proto__指向Function.prototype。
Function.prototype是个例外,它既是原型对象,又是函数对象。作为一个函数对象,它却没有prototype属性。
Object是函数对象,也通过new Function()创建,所以Object.__proto__指向Function.prototype。
Function.__proto__ === Function.prototype // true Function.constructor == Function //true Object.__proto__ === Function.prototype // true Object.constructor == Function //true Number.__proto__ === Function.prototype // true Number.constructor == Function //true Boolean.__proto__ === Function.prototype // true Boolean.constructor == Function //true String.__proto__ === Function.prototype // true String.constructor == Function //true Array.__proto__ === Function.prototype // true Array.constructor == Function //true RegExp.__proto__ === Function.prototype // true RegExp.constructor == Function //true Error.__proto__ === Function.prototype // true Error.constructor == Function //true Date.__proto__ === Function.prototype // true Date.constructor == Function //true
//所有的构造器都来自Function.prototype console.log(typeof Function.prototype) // function console.log(typeof Object.prototype) // object console.log(typeof Number.prototype) // object console.log(typeof Boolean.prototype) // object console.log(typeof String.prototype) // object console.log(typeof Array.prototype) // object console.log(typeof RegExp.prototype) // object console.log(typeof Error.prototype) // object console.log(typeof Date.prototype) // object
三、宿主对象
1、DOM对象
document,element,attribute,event,html。
2、BOM对象
window,document,location,history,navigator,XMLHttpRequest,screen,console。
3、自定义对象
//如何判断当前脚本运行在浏览器还是node环境中? 通过判断Global对象是否为window,如果不为window,当前脚本没有运行在浏览器中。