JavaScript学习笔记 继承关系

es5原型链的继承

	<head>
		<meta charset="utf-8">
		<title>继承关系</title>
		<script>
			//es5原型链的继承
			//Animal是父类   Person是子类
			function Animal(name){
				this.type='动物';
				this.say=function(){
					console.log('你好,我是'+name);
				}
			}
			var cat=new Animal('小猫');
			cat.say();
			console.log(cat);//__proto__是Object(父类是Object)
			function Person(){
				
			}
			//通过原型链实现继承关系
			Person.prototype=new Animal('人');
			var p=new Person();
			p.say();//通过继承的父类Animal的say()方法实现输出   你好,我是人
			console.log(p);//__proto__是Animal(父类是Animal)
		</script>
	</head>

在这里插入图片描述

es6实现继承 用extends关键字

在实现继承时,在访问当前Person1(this)对象或从子类构造器返回之前, 必须 要在子类的构造器中写super()调用父类的构造器

<scrpit>
	//es6 实现继承   用extends关键字
	class Animal1{
		constructor(name) {
		    this.type='动物';
			this.say=function(){
				console.log('你好,我是'+name);
			}
		}
		toString(){
			console.log('这里是动物的toString方法');
		}
	}
	//定义子类 Person1   extends Animal1
	//在实现继承时,必须要在子类的构造器中写super()调用父类的构造器
	class Person1 extends Animal1{
		constructor(){
			//此处的super可以帮助我们返回当前的Person1对象
			//在访问当前Person1(this)对象或从子类构造器返回之前,必须在子类的构造器中写super()调用父类的构造器
			super('人');//相当于es5中的:Person.prototype=new Animal('人');
		}
	}
	var p2=new Person1();
	p2.say();
	console.log(p2);
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值