es5和es6继承的关系和区别

172 阅读2分钟
//es5继承
//原型链继承
//父类型
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayhello = function() {
    console.log('hello');
};

function Student(grade) {
    this.grade = grade;
}
Student.prototype = new Person('zhangsan', 18);
let test = new Student(3);
console.log(test.grade); //3
test.sayhello(); //hello
console.log(test.name); //张三
console.log(test.constructor); //Person
/* 缺点
1. 原型对象的属性被所有实例共享
2. 创建子实例时无法向父构造函数传参
3. 必须先Student.prototype = new Person('zhangsan', 18)再为子类增加方法
4. 字类和父类无法区分,构造函数均指向Person
 */
//构造函数继承
function Student2(name, age, grade) {
    Person.call(this, name, age);
    this.grade = grade;
}
let test2 = new Student2('lisi', 19, 4);
console.log(test2.name); //lisi
console.log(test2.grade); //19
// test2.sayhello(); //test2.sayhello is not a function
/* 
缺点
1. 只能继承父类的实例属性和方法,不能继承原型
*/
//寄生组合式继承(最优)
function Student3(name, age, grade) {
    Person.call(this, name, age);
    this.grade = grade;
}
Student3.prototype = Object.create(Person.prototype); //创建一个proto指向Person.prototype的对象
Student3.prototype.constructor = Student3; //区分父类和子类

let test3 = new Student3('wangwu', 20, 5);
test3.sayhello(); //hello
console.log(test3 instanceof Person, test3 instanceof Student3) //true true
console.log(test3.constructor); //Student3
console.log(test3.__proto__); //Person
console.log(Student3.__proto__ === Function.prototype); // true

//es6class
// class其实就是es5中寄生组合式继承方式的语法糖(简化形式)
//es6class特性
/* 
1. class声明会提升但是不会初始化
2. class声明内部会启用严格模式
3. class的方法不可枚举
4. class的方法无原型对象,不能用new调用
5. class必须使用new调用
6. class内部无法重写类名
*/


//es6和es5继承区别
/* 
1. 子类构造函数的proto直接指向父类
2. class是先生成父类的实例,然后调用子类的构造函数修饰实例,这个差别使得ES6可以继承内置对象
3. es5中的继承是先生成子类的实例,然后调用父类的构造函数修饰实例
*/
class Animal {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    sayhello() {
        console.log('hello');
    }
}
class Dog extends Animal {
    constructor(name, age, color) {
        super(name, age);
        this.color = color;
    }
}
let dog1 = new Dog('maomao', 4, 'yellow');
dog1.sayhello; //hello
console.log(dog1.name); //maomao
console.log(Dog.__proto__ === Animal); //true