一、基本用法
- 原始类的写法 class关键字
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function() {
console.log("我可以打电话");
}
let huawei = new Phone("huawei", "5000")
huawei.call()
console.log(huawei)
- class的类用法,定义类,如何声明,以及实例化对象
class Phone{
//constructor 为固定方法名,后期直接用的构造方法名字,不一定要构造函数,没有构造函数也是可以的
constructor(brand,price){
this.brand = brand;
this.price = price;
}
//特有的方法
call(){
console.log("我可以打电话");
}
}
//实例化对象
let pingguo = new Phone("pingguo", "100")
pingguo.call()
console.log(pingguo)
二、类中的静态成员
- 实例对象和函数对象的方法是不相通的,属于静态成员
三、继承
- 使用es5实现类的继承
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function() {
console.log("我可以打电话");
}
let huawei = new Phone("huawei", "5000")
huawei.call()
console.log(huawei)
//智能手机
function smartPhone(brand,price,color,size){
//通过call方法去调用类中的构造方法,及继承
Phone.call(this,brand,price)
this.color=color
this.size=size
}
//设置子级构造函数的原型
smartPhone.prototype = new smartPhone
smartPhone.prototype.constructor= smartPhone
//声明子类的方法
smartPhone.prototype.photo=function(){
console.log('我可以拍照')
}
smartPhone.prototype.playGram=function(){
console.log('我可以玩手机')
}
const zhihui=new smartPhone('智慧',2499,'黑色','5.5yicun')
console.log(zhihui)
- 使用es6实现类的继承
class Phone{
//constructor 为固定方法名,后期直接用的构造方法名字
constructor(brand,price){
this.brand = brand;
this.price = price;
}
//特有的方法
call(){
console.log("我可以打电话");
}
}
class smartPhone extends Phone{
//extends 关键字表示继承父类
constructor(brand,price,color,size){
super(brand,price)
//super 关键字,完成对父类的构造方法的调用
this.color= color;
this.size= size;
}
//子类特有的方法,有了extends 继承父类的方法,则子类中就能调用父类的方法
photo(){
console.log('我可以拍照')
}
//子类特有的方法
playGram(){
console.log('我可以玩手机')
}
call(){
console.log('我是子类中重写父类的方法')
}
}
const xiaomi=new smartPhone('小米',88888,'白色','5.5yicun')
console.log(xiaomi)
四、子类对父类的重写
- 即完全重写,子类中不能使用super去调父类的方法
五、get和set方法
版权声明:本文为Smile_666666原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。