一.原型基本概念
原型与原型链常用来在js中实现继承,以及实现类的实例方法扩展。
- 显示原型:类/构造函数都是一个显式原型ptotype,本质上就是个对象。
- 隐式原型:每个实例都有一个隐式原型__proto__。
- 显与隐的关系:类显示原型protype等于其创建的实例的隐式原型__proro__。
原型链:当查找对象一个属性是先在自身找,找不到就沿着__proto__的__proto__向上查找,我们将__proto__形成的链条关系成为原型链。
二.原型公共方法
- 一般不要修改js默认对象原型上的方法,扩展也要谨慎
- 进行不要再js默认对象的原型上添加方法
- vue2 数组的双向绑定劫持就是重写了数组原型上的方法实现的
//求数组最大值
Array.prototype.max=function(){
//this就是当前数组,展开求最大
return Math.max(...this);
}
//求数组最大值
Array.prototype.min=function(){
return Math.min(...this);
}
三.继承
- student构造函数中继承
Peoplefunction Student(name,age,no){People.call(this,name.age);this.no =no;} - 继承原型链
Student.prototype = Object.create(People.prototype); - 修正Student构造函数
Student.prototype.constructor = Student;
//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);