继承第二节 原型继承和Es6继承

原型继承主要是继承*父类原型上的*属性或者方法。
1.创建一个空的构造函数
2.把空构造函数的原型等于父类的原型
3.把子类的原型等于空构造函数的实例对象
这样就达到了继承属性的目的(主要注意:手动修正constructor指向)
 
function Person(name,age){
        this.name = name;
        this.age = age;
    }
    Person.prototype.say = function(){
        alert('我的名字'+this.name);
    }
    Person.prototype.runing = function(){
        alert('我会跑');
    }

    function Coder(name,age,job){
        Person.call(this,name,age);
        this.job = job;
    } 
    function Xhh(){};
    Xhh.prototype = Person.prototype;
    Coder.prototype=new Xhh;
    Coder.prototype.constructor = Coder;//手动改变this的指向
    let c = new Coder('a',26,'超级码农');
    console.log(c);//此时c继承了Person的方法
 
 

Es6继承

class 类
ES6给我们提供了class的语法糖,可以通过class来创建类

具体语法

class 类名 {
constructor(形参){
//构造方法
}
方法名(){

          }
此处是不加,号的
方法名(){

                 }

定义方法:

(1)动态方法:(实例使用的方法)
这样的写法就等同于把方法挂在类的原型上了
方法名(){

                 }



(2)静态方法:(类使用的方法)
static 方法名(){  
                      
                        }

 
 

例如:

class Person {
        constructor(name,age){
            this.name = name;
            this.age = age;
        }
        say(){
            console.log('我的名字是'+this.name,'今年'+this.age);
        }
    }

    /*
        声明子类 extends 父类名 就继承父类了
    */

    class Coder extends Person {
        /*
            在子类constructor中添加属性的小技巧

            专属于子类的属性写在参数的前面,父类的属性放在后面
            这样一来,就能直接使用...arg

            ...arg
                把函数中的多余的参数放入数组中体现出来。

        */
        constructor(job,...arg){
            // console.log(this)
            super(...arg); //等同于调用父类,把多余的参数(和父类一样的属性)放到super中,达到继承父类属性的目的
            /*
                在继承里,写constructor必须写super
                super下面才能使用this,super有暂存死区(super上面不能使用this,用了就报错)
            */
            this.job = job;//自己私有的属性,直接this点即可
            console.log(arg);
        }
        codeing(){
            console.log('敲代码');
        }
        say(){
            console.log('哈哈');
        }

    }

    let c = new Coder('前端','a',20);
    let p = new Person('小明',30);
    console.log(c);
    // c.say();
    // p.say();
    // c.codeing();



猜你喜欢

转载自www.cnblogs.com/Allisson/p/9911054.html