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 之 继承关系,你学会了多少?欢迎在留言区评论!

发布了114 篇原创文章 · 获赞 9 · 访问量 1859

猜你喜欢

转载自blog.csdn.net/weixin_45794138/article/details/103964963
今日推荐