js中类的继承

只继承公有的

//es5
Children.prototype = Object.create(Parent.prototype)
//es6
Object.setPrototype(Children.prototype,Parent.prototype)

es5类的继承

//ES5的继承

    /*父类*/
    function Person(name) {
        this.name = name;
    }
    Person.prototype.showName = function () {
        console.log('我的名字是'+this.name);
    };
    /*子类*/
    function Student(name,skill) {
        Person.call(this,name);//继承属性,这里要改变this指向,如果有参数,要传参进去
        this.skill = skill;
    }

    /*继承*/

   /* function extend(Obj1,Obj2) {
        for ( item in Obj1){
            Obj2[item] = Obj1[item];
            return Obj2;
        }
    }

    extend(Person.prototype,Student.prototype);//原型继承方法
*/
    Student.prototype = new Person(); //直接继承方法

    Student.prototype.showSkill = function () {
        console.log("我的技能是:"+this.skill);
    };

    /*面向对象实例化*/
    var student = new Student("marin","跑路");

    console.log(student.name);
    student.showName();
    student.showSkill();

es6类的继承

 //ES6的继承

    /*父类*/
    class Person{
      constructor(name){
          this.name = name;
      }
      showName(){
          console.log(`我的名字是:${this.name}`)
      }
    }

     /*子类继承  extends 既能一下继承父类方法也可以一下继承父类属性 */
     class Student extends Person{
            constructor(name,skill){
                super(name);//用于拉取父类的构造函数里的属性 有参数就要传参数 也可用 args 实参集合
                this.skill = skill;
            }
         //子类重写showName 这样是不会改变父级的方法的,但是这样父级原来的想要在子类里面使用的就没有了

        /* showName(){
                console.log("我是子类重写的方法")
         }*/

         //另外一种子类重写放啊发,可以保证从父级继承来的方法能够执行的同时,还可以保证子类自己做自己的事;
         showName(){
                super.showName();//保证从父类继承来的方法执行
                console.log(`我是子类基于父类方法下,子类想要执行的额外操作`);//子类想要执行的操作
         }

         showSkill(){
             console.log(`我的技能是:${this.skill}`)
         }
     }

    /*面向对象实例化*/
   // let person = new Person("marin");
    let student = new Student("faker","饮水机");

    //person.showName();
    //console.log(student.name);
    student.showName();
    student.showSkill();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值