原型:js的每一个对象都有一个prototype对象,我们称之为显式原型,这个对象中包含一个constructor属性,它指向创建这个对象的构造函数,还有一个__proto__属性,我们称之隐式原型,它指向创建这个对象的构造函数的prototype显式原型。
原型链:是指当访问某个属性或方法时,会先在当前对象中查找,如果没有,则通过.__proto__去她的上一级构造函数的prototype中查找,如果还没有,就通过构造函数的prototype中的__proto__再向上一层查找,直到找到或者为null为止,这种通过原型进行的链式查找结构我们称之为原型链。
原型和原型链的作用:
1.实现了js的继承,原理是将子构造函数的prototype指向父构造函数的实例对象,以继承父构造函数的所有属性和方法,详细见下一章js中的继承方法。
ffunction Parent(){
this.name = 'xiaoming';
this.age = 10;
}
function Child(){
};
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let child1 = new Child();
console.log(child1);
2.实现啦实例的共用属性和方法;
例如:Array.prototype.max = function(){
return Math.max(…this);
}
3.可以实现求数组中最大和最小值的方法,在Array的prototype上添加最大和最小的共用方法;
Array.prototype.max = function(){
return Math.max(...this);
}
Array.prototype.min = function(){
return Math.min(...this);
}
let arr = [1,2,3,4,5,6];
console.log(arr.max(),arr.min()); //6 1