ES6之前的类
- 函数模拟: 构造函数(首字母大写),this.property;方法挂在prototype上:
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.showName = function(){
console.log(this.name);
}
复制代码
ES6的类 class
- 基本语法:
class Person{
constructor(name,age){ //构造方法,new调用的时候,立即执行
this.name = name;
this.age = age;
} //不要逗号
showName(){
return this.name;
}
}
let p1 = new Person('murphy',18);
复制代码
- 注意:
- class没有变量提升,必须先定义后使用;
- 方法名用变量: (react里受控表单里会用到)
let a = 'murphy';
let b = 'method';
class Person{
constructor(){
...
}
[a+b](){ //使用字符串拼接 作为方法名
console.log(this.name);
}
}
let p1 = new Person;
p1.murphymethod();
复制代码
- 关于this:解决了ES5 this指向的问题;
- class里面的取值函数getter存值函数setter;常用于封装相关;
- 静态方法: 类自身的方法,前面加关键字 static;可以被子类继承
类的继承
- ES6之前:
function Student (name, skill){
Person.call(this.name); //继承属性
this.skill = skill;
}
Student.prototype = new Person(); // 继承方法
let stu1 = new Student('murphy','技能');
复制代码
- ES6 的继承:
class Student extends Person{ //就这么简单
constructor(name,skill){
super(name); //继承父级属性和方法;
this.skill = skill; //添加子类的属性
}
showName(){
super.showName(); //父类方法的执行
console.log('子类的showName'); //子类的执行
}
showSkill(){ //添加子类的方法
return `技能是${this.skil}`;
}
}
let stu1 = new Student('murphy','逃学');
复制代码