JS 之 继承关系

今天跟大家分享下JS 之 继承关系的知识。

前言

在Javascript中如何实现继承关系的应用?Javascript继承概念:js是基于对象的,没有类的概念,所以实现继承,需要使用js的原型prototype机制或者用applay和call方法实现。

1 原型链继承

即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承。

为了让子类继承父类的属性(也包括方法),首先需要定义一个构造函数。然后,将父类的新实例赋值给构造函数的原型。

function parent(){
  this.name="garuda";
}
function child(){
  this.sex="man"
}
child.prototype=new parent();//核心:子类继承父类,通过原型形成链条
var test=new child();
console.log(test.name);
console.log(test.sex);

备注:在js中,被继承的函数称为超类型(父类、基类),继承的函数称为子类型(子类、派生类)。

使用原型继承存在两个问题:
一是面量重写原型会中断关系,使用引用类型的原型,
二是子类型还无法给超类型传递参数

2 借用构造函数继承

function parent(){
  this.name="garuda";
}
function child(){
  parent.call(this);//核心:借父类型构造函数增强子类型(传参)
}
var test =new parent();
console.log(test.name);

3 call()方法方式

call方法是Function类中的方法

call方法的第一个参数的值赋值给类(即方法)中出现的this

call方法的第二个参数开始依次赋值给类(即方法)所接受的参数

function test(str){
    alert(this.name + " " + str);
  }
var object = new Object();
object.name = "zhangsan";
test.call(object,"langsin");
//此时,第一个参数值object传递给了test类(即方法)中出现的this,
// 而第二个参数"langsin"则赋值给了test类(即方法)的str
  function Parent(username){
    this.username = username;
    this.hello = function(){
      alert(this.username);
    }
  }
  function Child(username,password){
    Parent.call(this,username); 
    this.password = password;
    this.world = function(){
      alert(this.password);
    }
  }
  var parent = new Parent("zhangsan");
  var child = new Child("lisi","123456");
  parent.hello();
  child.hello();
  child.world();

4 apply()方法方式

apply方法接受2个参数:
A、第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this
B、第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数

function Parent(username){
    this.username = username;
    this.hello = function(){
      alert(this.username);
    }
  }
  function Child(username,password){
    Parent.apply(this,new Array(username));
    this.password = password;
    this.world = function(){
      alert(this.password);
    }
  }
  var parent = new Parent("zhangsan");
  var child = new Child("lisi","123456");
  parent.hello();
  child.hello();
  child.world();

5 组合继承(原型链和构造函数组合)

function parent(){
  this.name="garuda";
}
function borther(){
  return this.name;
}
function child(){
  parent.call(this)
}
child.prototype=new parent();
var test=new parent();
console.log(test.borther())

6 总结

JS中的继承关系是很重要的技术知识了,经常会用到,不了解的童鞋需要加紧学习哦!

关于JS 之 继承关系,你学会了多少?欢迎在留言区评论!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祁娥安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值