1. 原型
1.1 概述
在JS中,我們創(chuàng)建的每個(gè)函數(shù)都有一個(gè)prototype屬性,該屬性的值為指向一原型對(duì)象的引用地址,該原型對(duì)象的初始屬性為constructor,值指向函數(shù)的引用地址,因此每個(gè)函數(shù)都有屬于他們自己的原型對(duì)象,如Number、String、Boolean、Object。
1.2 使用
Number.prototype、String.prototype、Boolean.prototype、Object.prototype為JS中各個(gè)類(lèi)型函數(shù)封裝好的原型對(duì)象,他們擁有各自基本的屬性和方法。
var n1 = new Number(1) //n1擁有Number.prototype所有方法和屬性
n1.toFixed(2) //返回"1.00"
2. 原型鏈
2.1 概述
對(duì)象含有proto屬性,指向?qū)?yīng)的原型對(duì)象,__proto__和prototype的基本關(guān)系為:對(duì)象.__proto__ === 函數(shù).prototype。
var n1 = new Number(1)
n1.__proto__ === Number.prototype //返回true
因?yàn)镹umber.prototype.__proto__ === Object.prototype,所以Number原型對(duì)象和Object原型對(duì)象成鏈?zhǔn)疥P(guān)系,因此稱(chēng)為原型鏈,同理String、Boolean。
2.2 原型鏈要點(diǎn)
i. Function作為函數(shù)同時(shí)也是對(duì)象,所以如下:
Function.__proto__ === Function.prototype //返回true
ii. Object函數(shù)的原型對(duì)象為原型鏈末端,所以如下:
Object.prototype.__proto__ === null //返回true