对于科班出身的程序员来说,class是啥玩意就不必哆嗦了,直接讲吧
在之前规范的写法是这样子的
//es5的常规用法
//手机
function phone(brand,price){
this.brand=brand;
this.price=price;
}
//添加方法
//prototype是函数对象上面预设的对象属性
phone.prototype.call=function(){
console.log("我可以打电话");
}
//实例化对象
let HUAWEI=new phone('华为',69999);
HUAWEI.call();
console.log(HUAWEI);
到了es6,我们可以运用class来处理了,一般我们在java怎么面向对象编程,这里就可以怎么面向对象编程。
//es6语法
class Phone{
//构造方法,固定
constructor(brand,price){
this.brand=brand;
this.price=price;
}
static name='手机';//静态属性,属于类,不属于对象
//方法必须使用该语法,不能使用es5的对象形式.
call(){
console.log("店电话");
}
}
let XIAOMI=new Phone("小米",1999);
//输出静态对象,啥事静态对象不知道的自己去查
console.log(XIAOMI);
console.log(XIAOMI.name);//undifine
console.log(Phone.name);//手机
那其他面向对象编程的内容有没有呢,当然有
比如继承
这是父类
class Phone{
//构造方法
constructor(brand,price){
this.brand=brand;
this.price=price;
}
//父类的成员函数
call(){
console.log("dianhua");
}
chongxie(){
console.log("父类还没从写的时候");
}
}
继承的子类
class SmartPhone extends Phone{
//子类构建方法
constructor(brand,price,color,size){
super(brand,price);
this.color=color;
this.size=size;
}
chongxie(){
console.log("子类重写函数");
// super.call();
}
photo(){
console.log("photo");
}
playgame(){
console.log("playgame");
}
get aa(){
console.log("aa");
}
}
这时候输出一下
const xiaomi=new SmartPhone('小米',5555,'black',40);
console.log("父类的东西"+xiaomi.brand);
console.log("子类的东西"+xiaomi.color);
xiaomi.chongxie();