首页 > 编程语言 > 详细

javascript实现继承方法

时间:2018-01-17 14:14:03      阅读:200      评论:0      收藏:0      [点我收藏+]

javascript继承概念:js是基于对象的,他没有类的概念,所以实现继承,需要使用js的原型prototype机制或者用applay和call方法实现

1、原型链继承

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

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、组合继承(原型链和构造函数组合)

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())

 

javascript实现继承方法

原文:https://www.cnblogs.com/wangpengfei8313/p/8302537.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!