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>