继承

1.借用构造函数
//借用构造函数 创建父函数
function Person(name,sex,age){
  this.name = name;
  this.sex = sex;
  this.age = age;
 }
 Person.prototype.sayHi = function(){
  console.log('安妮哈赛呦'+this.name);
 }
 function Student(name,sex,age,sorce){
 //利用call方法借用person构造函数,让this指向teacher
  Person.call(this,name,sex,age);
  this.sorce = sorce;
 }
 Student.prototype.play = function(){
  console.log('happy');
 }
var S1 = new Student('zs','男',89,10000);
 console.dir(S1);

// 借用构造函数只借用了属性 ,方法却没有继承

并没有继承父函数的方法

2.原型继承

所以我们将父函数的原型赋给子函数的原型看看

Student.prototype = Person.prototype;
//在赋值后改变了学生函数的原型的指向,再给Student函数添加方法,
//看看Person函数此时的内容
Student.prototype.play = function(){
  console.log('happy');
 }
 var p1 = new Person('zs','男',89);
 console.dir(p1);

在Person中也有了Student的方法

在这里插入图片描述
所以可见当teacher.prototype = person.prototype后,原型指向的是同一个对象,因此person也可以访问到teacher的方法
但当我们有多个函数要继承父函数的方法时,就会出现如下情况:

//新添加Teacher对象
function Teacher(name,sex,age,salary){
  // 利用call借用person构造函数,让this指向teacher
  Person.call(this,name,sex,age);
  this.salary = salary;
 }
Teacher.prototype = Person.prototype;
var t1 = new Teacher('zs','男',89,10000);
 console.dir(t1);

teacher也能访问到student的方法:
在这里插入图片描述
但我们不想出现这种情况,不想让所有的子函数都能访问到共同的方法

3.组合继承
//可以利用父类型将子函数的原型实例成一个Person对象,
//通过原型继承了父类型中的方法
//同时子类型的方法就成为了父类型的属性之一
Student.prototype = new Person();
//添加的类型要放在实例化之后,否则会被覆盖
 Student.prototype.play = function(){
  console.log('happy');
 }
 Teacher.prototype = new Person();
 Teacher.prototype.exam = function(){
  console.log('fire');
 }
 var S1 = new Student('zs','男',89,10000);
 console.dir(S1);
 var t1 = new Teacher('zs','男',89,10000);
 console.dir(t1);

在这里插入图片描述
互不影响
在这里插入图片描述

注:constructor指向创建该对象的构造函数
在这里插入图片描述
为防止被覆盖,在给原型赋值后应给constructor重新赋值

Student.prototype.constructor = Student;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值