ES6与ES5继承方式

ES5的继承

通过prototype或构造函数机制来实现

属性继承

父构造函数

function Father(name,age) {
    
    
  this.name = name; //此处 this 指向父构造函数的对象实例
  this.age = age;
}

子构造函数

function Son(name,age,score) {
    
    
  Father.call(this,name,age); //修改 Father 的 this 指向
  this.score = score;  //添加自己的属性
}
var son = new Son('刘德华',55,100);
console.log(son); //name:刘德华,age:55,score:100

prototype 属性

每一个构造函数都有一个 prototype 属性,指向一个对象。这个对象的所有属性和方法,都会被构造函数所拥有,可以把不变的方法定义在 prototype 对象上,这样所有对象实例都可以共享这些方法(节约内存资源)

混合继承

父构造函数

function Person(name, age) {
    
    
  this.name = name;
  this.age = age;
}
//添加方法
Person.prototype = {
    
    
  constructor: Person,
  sayHi() {
    
    
    console.log('hi,我是' + this.name);
  }
}
//属性继承
function Student(name, age) {
    
    
  Person.call(this, name, age)
}
//方法继承,替换原型,这里不能使用 Person.prototype ,下面给 Student 添加方法会影响 Person
Student.prototype = new Person();

//指回 Student
Student.prototype.constructor = Student;
Student.prototype.sayHello = function() {
    
    
  console.log('hello,我是' + this.name);
}

let student = new Student('张三', 18)
student.sayHi();    //hi,我是张三
student.sayHello(); //hello,我是张三

实例成员与静态成员

  1. 实例成员:构造函数内部通过this添加的成员
    • this.namethis.agethis.sing 都是
    • 只能通过实例化的对象访问
  2. 静态成员:在构造函数本身上添加的成员
    • sex = "男",sex 就是静态成员
    • 只能通过构造函数访问Star.sex

ES6继承

通过类实现继承

类和对象的含义

对象指的是一个具体的事物,在JavaScript中,字符串、数组、函数等都是特定的对象,类 是指这些对象的公共部分

constructor 函数

类里面有一个 constructor 函数,可以接收传递过来的参数,同时返回实例对象

  • constructor 函数只要 new 生成实例,就会自动调用,如果不写这个函数,类也会自动生成这个函数

  • 生成实例 new 不能省略,注意语法规范,类里面所有函数不需要加 function

创建类

class Star {
    
    
  constuctor(name.age) {
    
    
    this.name = name;
    this.age = age;
  }
}   
let ldh = new Star('刘德华',55) 
//ldh.name == 刘德华;ldh.age == 55

类的继承 extends

父类

class Father {
    
    
  constructor(x,y) {
    
    
    this.x = x;
    this.y = y;
  }
  sum() {
    
    
    console.log(this.x + this.y); //此处 this 指向 Father 类
  }
}

子类

class Son extends Father {
    
    
  constructor(x,y) {
    
    
    this.x = x;
    this.y = y;  //此处 this 指向 Son 类
  }
}
var son = new Son(1,2);
son.sum(); //报错

super 关键字

调用父类中的函数

class Father {
    
    
  constructor(x,y) {
    
    
    this.x = x;
    this.y = y;
  }
  sum() {
    
    
    //此处 this 指向 Father 类
    console.log(this.x + this.y); 
  }
  say() {
    
    
    return '我在';
  }
}

class Son extends Father {
    
    
  constructor(x,y) {
    
    
    super(x,y); //调用父类中的构造函数
  }
  say() {
    
    
    //调用父类中的 say() 函数
    console.log(super.say() + '你心里');
  }
}

let son = new Son(1,2);
son.sum(); //3
son.say(); //我在你心里

继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就执行子类的,没有就去父类找


三个注意点

  1. ES6中没有变量提升,必须先定义类,才能通过类实例化对象
  2. 类里面的共有属性一定要加 this
  3. 类里面的 this 指向问题
    1. cunstructor 里的this指向实例对象
    2. 方法里的 this 谁调用指向谁

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/108533748