### 1、类和对象的含义
对象指的是一个具体的事物,在JavaScript中,字符串、数组、函数等都是特定的对象,类 是指这些对象的公共部分
2、创建类
class声明,类名首字母大写
(1)语法
class Name { }
创建实例:let xx = new Name();
类必须使用 new 实例化对象
(2)constructor 函数
类里面有一个 constructor 函数,可以接收传递过来的参数,同时返回实例对象
class Star {
constuctor(name.age) {
this.name = name;
this.age = age;
}
}
let ldh = new Star('刘德华',55)
//ldh.name == 刘德华;ldh.age == 55
-
constructor 函数只要 new 生成实例,就会自动调用,如果不写这个函数,类也会自动生成这个函数
-
生成实例 new 不能省略,注意语法规范,类里面所有函数不需要加 function
3、类中添加共有方法
写在类里面的方法类似于 ES5 中写在原型上的方法
class Star {
constuctor(name.age) {
this.name = name;
this.age = age;
}
//添加方法
sing(song) {
console.log(this.name + song)
}
}
var ldh = new Star('刘德华',55);
ldh.sing('冰雨'); //刘德华冰雨
4、类的继承 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(); //报错
5、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(); //我在你心里
继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就执行子类的,没有就去父类找
6、三个注意点
(1)ES6中没有变量提升,必须先定义类,才能通过类实例化对象
(2)类里面的共有属性和方法一定要加 this
(3)类里面的 this 指向问题
cunstructor 里的this指向实例对象,方法里的 this 谁调用指向谁