class的基本使用
es5的使用方式
function Phone(name,price){
this.name = name;
this.price = price;
}
Phone.prototype.call= function(){
console.log(this.name);
}
let phone = new Phone('iphone',5600);
phone.call(); //iphone
es6 class的使用方式
class Phone{
constructor(name,price){
this.name = name;
this.price = price;
}
call(){
console.log(this.name);
}
}
let phone = new Phone('iphone',5600);
phone.call(); //iphone
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Phone{
constructor(name,price){
this.name = name;
this.price = price;
}
static change(){
console.log("我是静态方法");
}
call(){
console.log(this.name);
}
}
let phone = new Phone('iphone',5600);
phone.call();//iphone
Phone.change();//我是静态方法
phone.change();//phone.change is not a function
注:被static修饰的属性或者方法,应被类名直接调用
私有属性和方法
class Point {
#x;
constructor(x = 0) {
this.#x = +x;
}
get x() {
return this.#x;
}
set x(value) {
this.#x = +value;
}
}
上面代码中,#x就是私有属性,在Point类之外是读取不到这个属性的。由于井号#是属性名的一部分,使用时必须带有#一起使用,所以#x和x是两个不同的属性。
继承
es5
function Phone(brand,price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function() {
console.log("打电话"+this.brand);
}
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.photo = function () {
console.log("可以牌照"+this.color);
}
let sp = new SmartPhone("huawei",2300,'black',6.5)
sp.call();//打电话huawei
sp.photo();//可以牌照black
es6
class Phone{
constructor(name,price){
this.name = name;
this.price = price;
}
static change(){
console.log("我是静态方法");
}
call(){
console.log(this.name);
}
}
class SmartPhone extends Phone{
constructor(brand,price,color,size){
super(brand,price);
this.color = color;
this.size = size;
}
photo(){
console.log("可以牌照"+this.color);
}
}
let phone = new SmartPhone("iphone",2300,'black',6.5);
phone.photo(); //可以牌照black
SmartPhone.change();//继承了父类的静态方法
get和set
class Phone{
#price;
get price(){
return this.#price;
}
set price(newVal){
this.#price = +newVal
}
call(){
console.log(this.#price);
}
}
let ph = new Phone()
ph.price = 5.5;
ph.call()