原型与原型链常用来在js中实现继承,以及实现类的实例方法扩展。
一、什么是原型、原型链
原型:每一个类(构造函数)都有一个显示原型prototype,每一个实例都有个隐式原型__proto__;类的prototype等于其实例的__proto__,即:
var arr=[1,2,3];
Array.prototype===arr.__proto__;
var obj={};
obj.__proto__===Object.prototype;
//Array Object为类,arr、obj分别为它们的实例
原型链:当查找对象一个属性是先在自身找,找不到就沿着__proto__的__proto__向上查找,我们将__proto__形成的链条关系成为原型链。
二、实例公用方法扩展
所有数组将拥有max、min方法。
//求数组最大值
Array.prototype.max=function(){
//this就是当前数组,展开求最大
return Math.max(...this);
}
//求数组最大值
Array.prototype.min=function(){
return Math.min(...this);
}
三、js实现继承
3.1 class的extends
class Student extends People{
constructor(name,age,no){
//类中继承构造函数
super(name,age)
...
}
}
3.2 原型链继承
通过创建类来解释原型与原型链之间的关系,及如何实现继承。
//01创建people类
function People(name,age){
this.name=name;
this.age=age;
}
//02 给people显示原型添加eat方法
People.prototype.eat=function(){
console.log(this.name+"正在吃饭");
}
//03创建学生类,继承People类
function Student(name,age,no){
People.call(this,name,age);
//定义学号
this.no=no;
}
//04让Student原型链继承PeoPle的原型链
Student.prototype=Object.create(People.prototype);
//05修正Student显示原型上的构造函数
Student.prototype.constructor=Student;
//06 在Student显示原型链上添加方法
Student.prototype.study=function(){
console.log(this.name+"正在努力学习,daydayup");
}
//07 构建Student的实例s1
var s1=new Student("小白",18,9527);
通过后台打印,可得出如下结果: