ES6引进了class的概念,作为对象的模板,可以使用关键字class来定义类。
使用class定义类,不需要添加function关键词,如下定义一个名为Person的类,直接使用class Person
;
在Person类中创建一个work方法,直接使用work(){}
。
class Person{ constructor(name,age){ this.name=name; this.age=age; } work(){ console.log('Person 工作~~') } } class Student extends Person{ constructor(name,age,major){ //调用父类的构造函数,并传参 super(name,age); this.major=major; } //子类重写(覆盖)了父类函数:父类函数内容太广泛太笼统,不具体,并不能完成体现子类的特点 work(){ //用super.xxx 可以获取父类的成员 super.work(); console.log("学生的工作就是学习") } } var s = new Student("jack",30,'Web'); console.log(s); s.work();
创建一个Student类继承Person类,需要使用extends关键词。子类可以使用super来获取父类的成员。
子类中如果创建和父类同名的方法,会覆盖父类的方法。
被static修饰的成员,不是通过对象调用的,而是通过类名调用。
被static修饰的成员归属类,而不是对象。
被static修饰的成员是在创建类的时候一起创建的。
平时用过的静态成员大多数都是工具函数。
class Person{ constructor(name,age){ this.name=name; this.age=age; } } class Student extends Person{ constructor(name,age,major){ super(name,age); this.major=major; } //静态成员 static role='kid' static getMyName(){ console.log('getMyName : ' + this.name);//返回当前类名:Student } } var s = new Student("jack",30,'Web'); //通过类名调用静态函数 Student.getMyName(); //常用的静态函数 console.log(Date.now());
私有成员的访问范围仅限于class大括号内,需要在名称前加#
,私有属性必须在constructor之前定义一下。
class Animal{ //私有成员在constructor之前定义一下; #b; constructor(a,b){ this.a=a; //使用私有成员 this.#b=b; } run(){ console.log("this.#b : " + this.#b) } #stop(){ console.log("stop") } } var x = new Animal("123","456") console.log(x.a) x.run(); x.stop();//x.play is not a function
不能在最后使用实例调用stop函数。只能在class中使用。
try{}catch(){}
try { //在此运行可能会出错误的代码 } catch(err) { err;可以获得出错的信息 //在此处理错误 }
主动抛出异常
function play(){ throw "当前函数不可用" }