ES6提供了更接近传统语言的写法,引入了Class(类)这个概念,作为对象的模板,通过class关键字,可以定义类,基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
1.ES5的写法
function Phone(brand, price){
this.brand = brand //对实例对象的属性做初始化操作
this.price = price
}
//添加方法,通过原型对象添加,这样可以实现复用
Phone.prototype.telePhone = function(){
console.log('我可以打电话')
}
//实例化对象
let HuaWei = new Phone('华为', 9999)
HuaWei.telePhone()
console.log(HuaWei)
2.ES6的写法
class Phone{
//构造方法,名字不能修改
constructor(brand, price){
this.brand = brand
this.price = price
}
//方法必须使用该语法,不能使用ES5的对象完整形式
telePhone(){
console.log("我可以打电话!")
}
}
let onePlus = new Phone("1+", 1999)
console.log(onePlus)
class静态成员
ES5举例
function Phone(){
}
Phone.name = '手机'
Phone.change = function(){
console.log("我可以改变世界")
}
Phone.prototype.size = '5.5'
let nokia = new Phone()
console.log(nokia.name) //undefined
//实例对象是没有构造函数身上的属性的
nokia.change() // type error, nokia.change() is not a function
console.log(nokia.size) //5.5
ES6写法
对于static标注的属性和方法,它属于类,而不属于实例对象
class Phone{
//静态属性
static name = '手机'
static change(){
console.log('我可以改变世界')
}
}
let nokia = new Phone()
console.log(nokia.name) //undefined
console.log(Phone.name) //手机
对象继承
ES5写法
//父类 手机
function Phone(brand, price){
this.brand = brand
this.price = price
}
Phone.prototype.telePhone = function(){
console.log('我可以打电话')
}
//智能手机
function SmartPhone(brand, price, color, size){
Phone.call(this, brand, price)
this.color = color
this.size = size
}
//设置子级构造函数的原型
SmartPhone.prototype = new Phone
SmartPhone.prototype.constructor = SmartPhone
//声明子类的方法
SmartPhone.prototype.phone = function(){
console.log('我可以拍照')
}
SmartPhone.prototype.playGame = function(){
console.log('我可以玩游戏')
}
const chuizi = new SmartPhone('锤子',2499,'黑色','5.5')
console.log(chuizi)
ES6写法
class Phone{
//构造方法
constructor(brand, price){
this.brand = brand
this.price = price
}
//父类的成员属性
telePhone(){
console.log("我可以打电话")
}
}
class SmartPhone extends Phone{
//构造方法
constructor(brand, price, color, size){
//super相当于父类的constructor方法
super(brand, price) //Phone.call(this, brand, price)
this.color = color
this.size = size
}
phone(){
console.log('拍照')
}
playGame(){
console.log('玩游戏')
}
}
const xiaomi = new SmartPhone('小米', 799, '黑色', '4.5')
console.log(xiaomi)
子类对父类方法的重写
class Phone{
constructor(brand, price){
this.brand = brand
this.price = price
}
telephone(){
console.log('我可以打电话')
}
}
class SmartPhone extends Phone{
constructor(brand, price, color, size){
super(brand, price)
this.color = color
this.size = size
}
phone(){
console.log('拍照')
}
playGame(){
console.log('玩游戏')
}
//可以在子类声明一个跟父类同名的方法
telephone(){
console.log('可以进行视频通话')
}
}
const xiaomi = new SmartPhone('小米', 799, '黑色', '4.5')
xiaomi.telephone() //可以进行视频通话
//值得注意的是,子类是不能调用父类的同名方法的
get和set
class Phone{
get price(){
console.log('价格属性被读取')
return 'ew'
}
set Price(){
console.log('价格属性被修改了')
}
}
//实例化对象
let s = new Phone()
console.log(s.price)
s.price = 'free'
//使用场景 get通常来对对象的动态属性进行封装