js中的继承

11. 继承

1. 原型链继承

// 生成一个人的构造函数
function Person() {
  this.person = "人"
}
// 在原型中存储一个方法
Person.prototype.say = function () {
  console.log("我是个人");
}

// Student()构造函数继承人构造函数
function Student() {
  this.student = "学生"
}

// 一个构造函数继承于另一个构造函数 ,如果能调用到Person身上的原型方法,那就说明继承成功了
// 方法1.可以直接改变构造函数的原型链指向
// 原型指向person的一个实例对象,画图表示
Student.prototype = new Person()
const student = new Student()

// 根据图,我们知道了student的隐式原型链
// 1.先查找Student的实例对象自身身上的属性方法
// 2.如果找不到,查找Person实例对象身上的属性方法
// 3.如果找不到,就会在Person构造函数的原型对象上查找属性方法
// Student的实例对象属性
console.log(student.student);
// Person的实例对象属性
console.log(student.person);
// Person原型对象上的方法
student.say()

// 说明person并不是student对象上的属性,而是person原型链上的属性,所以如果想要用如下方式改变,是不会走原型链的,而是在student对象上新增一个person属性并赋值
student.person = "学生对象的人"
console.log(student.person)
console.log(student.__proto__.person)
console.log(student)

在这里插入图片描述

2. call函数

function A() {
  this.name = "jack"
  this.age = 20
}
function B() {
  this.name = "tom"
}
B.prototype.say = function(){
  console.log(this.name)
  console.log(this.age)
}
const a = new A()
const b = new B()
b.say.call(a)
// call可以改变函数的this指向
// 如:b.say.call(a)
// b调用say函数时, 本身的this应该指向b对象,但通过call, 可以改变say中的this, 让say中的this指向a对象,所以它才能访问到age(b中不存在age)

3. call继承(借用构造函数)

function Person(){
  this.name = "人"
}

Person.prototype.say = function(){
  console.log("我是个人");
}

function Student(){
  // 这个相当于使用Student的this执行person函数
  // 所以此种方法可以得到所有在Person构造函数里的属性,也就是在this上定义的属性
  Person.call(this)
  this.age = 12
}

const student = new Student()
const person = new Person()

console.log(student.name)
console.log(student.text)

person.say()
// 说明,student并没有继承到person中的原型链的方法,它的本质其实只是调用了person方法,拿到了Person中的属性,并没有拿到原型链,除非和原型链继承一起用
// student.say() // 报错,找不到该函数

Student.prototype = new Person()

// 两种方法一结合,Student就继承了Person的所有东西,并且属性也在自身上.

4. 构造函数和原型链继承集结合

function Person(){
  this.name = "人"
  this.age = 10
}

Person.prototype.say = function() {
  console.log("我是"+this.name)
}

function Student(){
  // 继承Person的属性
  Person.call(this)
  // 存入自己的属性
  this.school = "八一中学"
}

// 继承Person原型链的方法
Student.prototype = new Person()

const student = new Student()

console.log(student);
student.name = "学生"
student.say()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值