原型与原型链

        原型与原型链常用来在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);

 通过后台打印,可得出如下结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值