ES6——class(类)的介绍
ES6提供了更接近于传统语言的写法,引入了class(类)这个概念,作为对象的模板,通过class关键字,可以让对象原型的写法更加清晰,更像面对对象编程的语法
- class声明类,constructor定义构造函数初始化
class Phone1 {
constructor(brand, price) {
this.brand = brand;
this.price = price;
}
call() {
console.log('我能打电话');
}
}
let onePlus = new Phone1('1+', 1999);
console.log(onePlus);
在这里与构造函数区别一下
function Star(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
}
Star.prototype.talent=function(){
console.log('我会演小品');
}
let bp1=new Star('jisoo',25,'女');
console.log(bp1);
Star.talent();
- extends继承父类,super调用父级构造方法
class Phone {
constructor(brand, price) {
this.brand = brand;
this.price = price;
}
call() {
console.log('我能拍照');
}
}
class SmartPhone extends Phone {//Phone为要继承的父类
constructor(brand, price, color, size) {
super(brand, price);//super里面的属性为继承父类的属性,新的属性在外面补充
this.color = color;
this.size = size;
}
photo() {
console.log('我能拍照');
}
}
let xiaomi = new SmartPhone('xiaomi', 1999, 'red', 15.6);
console.log(xiaomi);
xiaomi.call();
- static定义静态方法和属性
/* class静态成员 */
class Star {
//静态属性
static name = 'jisoo';
static habit = function() {
console.log("That's a pity");
}
}
let jisoo = new Star();
console.log(Star.name); //jisoo
console.log(jisoo.name); //undefined
- 父类方法可以重写
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
money() {
console.log('我能赚钱');
}
}
class Son extends Father {
constructor(name, age, gender) {
super(name, age);
this.gender = gender;
}
money() {
console.log('我也能赚钱');
}
}
let son = new Son('jisoo', 25, '女');
console.log(son);
son.money();