javascript中实现继承的方式

js中的继承

  js中的继承和java中的继承不一样,js中的继承主要是通过对父类进行复制来实现的。今天刷题的时候想起来这个问题,之前看了一遍,还是没有记很清楚,所以我就查阅了资料外加网上搜索,总结了几条,那么到底该怎样实现呢,今天就来谈谈。
  首先,一个公共的父类,代码如下:

//公共父类
function People(name,age){
    this.name = name;
    this.age = age;
    this.friends=['lili','candy','tom'];
    //内部方法
    this.sayAge = function(){  
        console.log('i am '+this.age+' years old now');
    }
}
//原型方法
People.prototype.sayName = function(){
   console.log(this.name+' 现在 '+this.age+' 岁!');
}

1、原型继承
  这种方式是大家很容易就能想到的,几乎是脱口而出。主要实现方法是:将子类的原型作为父类的实例(Child1.prototype = new People())

//子类
function Child1(){

} 
Child1.prototype = new People();  //核心
Child1.prototype.name = 'tyj';
Child1.prototype.age = 20;
var child1 = new Child1();

console.log(child1.name);       
console.log(child1.friends);     //['lili','candy','tom']  
child1.sayName();

原型继承的缺点:
  1)引用类型值的原型属性会被所有实例共享
  2)不能向父类传递参数

基于第一个缺点举个栗子:

var child2 = new Child1();
child2.friends.push('lucy');
console.log(child2.friends);    //['lili','candy','tom','lucy']
console.log(child1.friends)    //['lili','candy','tom','lucy']

基于第二个缺点举个栗子:

function Child1(name){
} 
var child2 = new Child1("一马平川");
var child22 = new Child1("顺顺利利");
child2 .sayName();        //undefined现在undefined岁!
child22 .sayName();      //undefined现在undefined岁!
//如果想设置参数,可以在Child1的原型上添加

2、构造函数继承
  使用构造函数实现继承,主要是借用了call()和apply()方法来实现

//子类
function Child2(name){
    People.call(this);    //调用父类,继承People
    this.name = name || 'Jack';
    this.age = age || 15;
}
var child2 = new Child2();
console.log(child2.name);
child2.sayAge();    //父类内部方法,可以调用
child2.sayName();  //父类原型上方法,调用时报错

构造函数继承的缺点:
  1)不能调用父类的原型方法,只能是内部方法
  2)每个子类都有父类实例函数的副本,影响性能

3、组合继承
  这种方式是将原型继承和构造函数继承的方式组合在一起,原型链实现对原型属性和方法的继承,构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又能够保证每个实例都有它自己的属性。这也是 JavaScript 最常用的继承模式

//子类
function Children(){
    People.call(this,'candy',20);
}
Children.prototype = new People();
var child3 = new Children();
console.log(child3 .name);
child3 .sayName();   //原型上定义的方法

4、寄生组合式继承

function Child4(name,age){
    People.call(this);
    this.name = name;
    this.age = age;
}
// 创建只继承原型对象的函数
function init(parent,child){     //参数:父类型构造函数和子类型构造函数。
    var prototypes = new Object(parent.prototype);   // 创建一个原型对象副本
    prototypes.constructor = child;    // 设置constructor属性,重写原型而失去的默认的 constructor 属性
    child.prototype = prototypes;
}
init(People,Child4);

var child4= new Child4('heihei',18);
console.log(child4.name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值