ES6 class 类

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对 象的模板。通过 class 关键字,可以定义类。基本上,ES6 的 class 可以看作只是 一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象 原型的写法更加清晰、更像面向对象编程的语法而已。
知识点:

1. class 声明类

// ES5 的写法
//手机
function Phone(brand, price){
    this.brand = brand;
    this.price = price;
}
//添加方法
Phone.prototype.call = function(){
    console.log("我可以打电话!!");
}
//实例化对象
let hw = new Phone('华为', 5999);
hw.call();  // 我可以打电话!!
console.log(hw); // Phone {brand: '华为', price: 5999}

// ES6 class 类的写法
class Shouji{
//构造方法 名字不能修改
	constructor(brand, price){
	    this.brand = brand;
	    this.price = price;
	}
//方法必须使用该语法, 不能使用 ES5 的对象完整形式
	call(){
	    console.log("我可以打电话!!");
	 }
}
let onePlus = new Shouji("1+", 1999);
console.log(onePlus); // Shouji {brand: '1+', price: 1999}

2. constructor 定义构造函数初始化

3. extends 继承父类

class Phone{
    //构造方法
    constructor(brand, price){
        this.brand = brand;
        this.price = price;
    }
    //父类的成员属性
    call(){
       console.log("我可以打电话!!");
    }
 }
class SmartPhone extends Phone {
    //构造方法
    constructor(brand, price, color, size){
        super(brand, price);// Phone.call(this, brand, price)
        this.color = color;
        this.size = size;
    }
	photo(){
        console.log("拍照");
    }
	playGame(){
        console.log("玩游戏");
    }
	call(){
        console.log('我可以进行视频通话');
    }
}
const xiaomi = new SmartPhone('小米',799,'黑色','4.7inch');
xiaomi.call(); // 我可以进行视频通话
xiaomi.photo(); // 拍照
xiaomi.playGame(); // 玩游戏

4. super 调用父级构造方法

5. static 定义静态方法和属性

// 实例对象和函数对象是不相通的,上面的函数对象属于类的静态成员
function Phone(){}
Phone.name = '手机';
Phone.change = function(){
     console.log("我可以改变世界");
}
Phone.prototype.size = '5.5inch';
let nokia = new Phone();
console.log(nokia.name); // undefined
console.log(nokia.size); // 5.5inch
console.log(Phone.name); // undefined
nokia.change(); // 报错 Uncaught TypeError: nokia.change is not a function

// 静态属性和方法
class Phone{
    //静态属性
    static name = '手机';
    static change(){
        console.log("我可以改变世界");
    }
}
let nokia = new Phone();
console.log(nokia.name); // undefined
console.log(Phone.name); // 手机

6. 父类方法可以重写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值