EE6有了class > 创建类;
ES6类
constructor 是一个构造器,用来接收形参;
class Person {// constructor是一个构造方法, 用来接收参数constructor(name, sex) {this.name = name;this.age = 18;this.sex = sex;}// 类的方法run(){return console.log(`${this.name}今年${this.age}岁,性别${this.sex}`);}}const ming = new Person('小明','男');ming.run()// class 调用另一个class.class Desk{constructor(){this.xixi="前端伪大叔";}}class Box{constructor(){// 这里没有用this哦,直接返回一个全新的对象return new Desk();}}const desk = new Desk()var box=new Box();console.log(desk.xixi);console.log(box.xixi);
ES6继承
继承需要使用关键字extends来继承另一个类。
使用constructor后必须使用super();
super是用来给父类里面constructor里面的形参传参的。
// 第一个类
class Person {
// constructor是一个构造方法, 用来接收参数
constructor(age) {
this.age = age;
}
// 类的方法
presonFun(){
console.log('执行',this.age);
return console.log(`person方法${this.age}`);
}
}
//第二个类
class Animal{
constructor(name){
this.name = name;
}
animalFun(){
return console.log(`animal方法${this.name}`);
}
}
// 继承类
class Bird extends Person {
constructor(sex){
// super 里面参数之间传给父类。
// 等同于 Animal.call(11)
super('preson')
this.sex = sex
}
birdFun(){
// 之间调用Person的方法
this.presonFun()
// console.log(this.age);
return console.log(`bird方法${this.sex}`);
}
}
// 自己传bird super(父类传preson)
const bird = new Bird('bird');
bird.birdFun()
bird.presonFun()
//
new Person(`直接调用Preson方法执行成功!`).presonFun()
