原生继承和ES6中的继承

在原生中的继承,例子如下:

function Person(name,age){
      this.name = name;
      this.age = age;
   }
Person.prototype.say = function(){
     console.log('我是'+this.name);  
 }

类 构造函数,属性写在构造函数中,方法写在原型下;现有一个Coder类想要继承Person类:

function Coder(name,age){
     Person.call(this,name,age);
}

在子类构造函数中, 通过父类Person.call(this) 继承属性;

Coder.prototype = new Person();
Coder.prototype.constructor = Coder;

在子类构造函数中,通过子类的 prototype = new 父类的实例化对象 继承方法 ;Coder的原型对象下 本来constructor指回Coder构造函数 需要手动添加 constructor属性 = Coder

var c1 = new Coder('xx',19);
var c2 = new Coder('yy',20);
c2.say();
console.log(c1,c2);

这样就实现了继承,子类可以调用父类的继承父类的属性和方法,相比ES6中的继承,这个继承方法有点难理解,以下为ES6中继承;

在ES6中的继承,例子如下:
父类Person:

    class Person{
        constructor(name,age){
            this.name = name;
            this.age = age;
        }
        say(){
            console.log('haha'); 
        }
        static xx(){
            console.log("xxxx");     
        }
    }
    let p1 = new Person('zc',20);
    console.log(p1);
    p1.say();

现有一个Coder类想要继承Person类:

class Coder extends Person{
        constructor(name,age,num){
            super(name,age);
            //coder自己的属性
            this.littlehair = num;
        }
        coding(){
            console.log("hello,world");
        }
    }
    let c1 = new Coder('zs',48,10);
    console.log(c1);
    c1.coding();
    c1.say();
    Person.xx();

用一个super()就可以继承父类的属性,也可以自己单独加子类的属性;
ES6实现类的继承,明显更容易被理解;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值