ES6扩展内容(Class)

1,695 阅读2分钟

一,使用class创建对象

class 类名{
    constructor(参数,参数){
        this.属性=参数;        this.属性=参数;
    }
    method(){  //对象中简写方法,省略了function。不要与箭头函数搞混了。
    }
}

例子:

 class NBAPlayer{        constructor(name,age,height){            this.age=age;            this.height=height;            this.name=name;        }        say(){            console.log("我是"+this.name+".今年"+this.age)        }    }    let p1=new NBAPlayer("库里","30")
    p1.say();

注意:

  • class是关键字,后面紧跟类名,类名首字母大写,采取的是大驼峰命名法则。类名之后是{}。
  • 在{}中,不能直接写语句,只能写方法,方法不需要使用关键字
  • 方法和方法之间没有逗号。不是键值对。

二,使用extends实现继承

格式:

class 子类 extends 父类{
    constructor(参数){
        super(参数)
        this.属性=值
    }
}

注意:

  • 使用extends关键字来实现继承
  • 在子类中的构造器constructor中,必须要显式调用父类的super方法,如果不调用,则this不可用

例子:

class  MVP extends NBAPlayer{        constructor(name,age,height,year){
        super(name,age,height)
        this.year=year;
   }
   showMVP(){
         console.log("我是"+this.name+".我是"+this.year+"年的MVP")
}
}
 let p1=new NBAPlayer("库里","30")
    p1.say();

三,类的静态方法static

  • 直接通过类名来访问的方法就是静态方法。如:Math.abs();这里的abs()是静态方法

  • Array.isArray();isArray()是静态方法,在方法名前加static 就可以了。

四,类的静态属性static

  • 直接通过类名来访问的属性就是静态属性。
  • 如:Math.PI;这里的PI是静态属性。实现的方式在属性名前加static 就可以了。

五,类的修饰器

  • 装饰器可以修饰类 类的属性 类的原型上的方法

  • 修饰的时候 就是把这个类 属性… 传递给修饰的函数

@flag('哺乳类')
class Animal {
    @readonly(123) 
    PI = 3.14;
    name = 'xxx'; // 实例上的属性  并不是原型上的属性
    @before
    say(a,b,c){
        console.log('说话',a,b,c,this.a)
    }
    a(){return 1}
}
// 1) 类的静态属性
 function flag(value){
    // consructor 当前类
    return function(consructor){
        consructor.type=value
    }
}
console.log(Animal.type)
// 2) 类的属性 (实例上的属性)

function readonly(target,property,descriptor){
    descriptor.writable = false;
    // console.log(target == Animal.prototype); // 类的原型
}

let animal = new Animal();
// animal.PI = 3.15

// target = Animal.prototype 类的原型
// property 装饰的属性
// descriptor 属性的描述器
function before(target,property,descriptor){
    let oldSay = descriptor.value;
    descriptor.value = function(){
        console.log('before');
        oldSay.call(target,...arguments);
    }
}
animal.say(1,2,3);