1. 原型
1.1 概述
在JS中,我们创建的每个函数都有一个prototype属性,该属性的值为指向一原型对象的引用地址,该原型对象的初始属性为constructor,值指向函数的引用地址,因此每个函数都有属于他们自己的原型对象,如Number、String、Boolean、Object。
1.2 使用
Number.prototype、String.prototype、Boolean.prototype、Object.prototype为JS中各个类型函数封装好的原型对象,他们拥有各自基本的属性和方法。
var n1 = new Number(1) //n1拥有Number.prototype所有方法和属性
n1.toFixed(2) //返回"1.00"
2. 原型链
2.1 概述
对象含有proto属性,指向对应的原型对象,__proto__和prototype的基本关系为:对象.__proto__ === 函数.prototype。
var n1 = new Number(1)
n1.__proto__ === Number.prototype //返回true
因为Number.prototype.__proto__ === Object.prototype,所以Number原型对象和Object原型对象成链式关系,因此称为原型链,同理String、Boolean。
2.2 原型链要点
i. Function作为函数同时也是对象,所以如下:
Function.__proto__ === Function.prototype //返回true
ii. Object函数的原型对象为原型链末端,所以如下:
Object.prototype.__proto__ === null //返回true
网友评论