ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对 象的模板。通过 class 关键字,可以定义类。基本上,ES6 的 class 可以看作只是 一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象 原型的写法更加清晰、更像面向对象编程的语法而已。
类:是一个抽象的概念
对象:是类的实例化
目录
知识点:
-
class 声明类
-
constructor 定义构造函数初始化
class Shoujie { constructor(price,branch){ this.price = price; this.branch = branch; } call(){ console.log(`${this.price}:${this.branch}`); } } let huawei = new Phone(2859,"华为"); huawei.call();
-
static 定义静态方法和属性
class Shouji { static name = "手机"; static change(){ console.log("可以改变 世界"); } constructor(price,branch){ this.price = price; this.branch = branch; } call(){ console.log(`${this.price}:${this.branch}`); } }
-
extends 继承父类
-
super 调用父级构造方法
-
父类方法可以重写
function Phone(price,branch){
this.price = price;
this.branch = branch;
}
Phone.prototype = {
call:function(){
console.log(`${this.price}:${this.branch}`);
}
}
function SmartPhone(price,branch,color,size){
Phone.call(this,price,branch);
this.color = color;
this.size = size;
}
SmartPhone.prototype = new Phone();
SmartPhone.prototype.photo = function(){
console.log("我可以拍照");
}
let sp = new SmartPhone(2999,"小米","black","5.5inch");
sp.call();
sp.photo();
class Shouji {
static name = "手机";
constructor(price,branch){
this.price = price;
this.branch = branch;
}
call(){
console.log(`${this.price}:${this.branch}`);
}
}
class xiaoshouji extends Shouji {
constructor(price,branch,color,size){
super(price,branch);
this.color = color;
this.size = size;
}
photo(){
console.log("我可以拍照");
}
playGame(){
console.log("我可以打游戏");
}
call(){
console.log("我可以视频通话");
}
}
let huawei = new xiaoshouji(2999,"华为","red","5.5inch");
console.log(huawei);
huawei.playGame();
huawei.call();
huawei.photo();