ES6通过class关键字定义类。class是—个 语法糖,是构造函数的另—种写法。?
基本用法
//类声明(不可重复声明)
class Point {
constructor(x,y){
this.x = x;
this.y = y;
}
add(){
return this.x + this.y;
}
}
//类的实例化(必须使用new命令)
let p1 = new Point(2, 1);
let p2 = new Point(3, 1);
- constructor方法对应ES5的构造函数Point, new时会自动调用该方法。其中的this代表实例对象。一个类必须有constructor方法,如没有显式定义,会默认添加—个空的constructor方法。?
- 类中的自定义方法如add均定义在prototype上面。每个方法包括constructor之间无需用,隔开。?
静态方法
class Foo {
static classMethod() {
return'hello';
}
}
Foo.classMethod() //'hello'
var foo = new Foo();
foo.classMethod()
//TypeError: foo.classMethod is not a function
如果在方法前加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用, 即“静态方法"。静态方法中的this指向类,而不是实例。
实例属性头部写法
class Example {
a = 2;
getValue () {
console.log(this.a);
}
}
实例属性除了定义在constructor()方法里面的 this上面,也可以定义在类的头部。直观,— 眼就能看出这个类有哪些实例属性。?
取值函数getter和存值函数setter
class Person {
constructor() {
this._name = "";
}
getname() {
console.log('getname');
return `名字${this._name}`;
}
setname(val) {
console.log('setname');
this._name = val;
}
}
const person = new Person();
person.name = 'Xiao1';
console.log(person.name);
//setname
//getname
//名字Xiao
类似访问器属性。在函数前加get和set表示读取属性和设置属性时调用的函数,其中set函数接收一个参数,表示属性设置的值。getter与setter需同时设置。?
extends继承?
子类继承父类,使用extents关键字。
super可以当函数和对象使用。?
super作为函数调用时,代表父类的构造函数,相当于Person.call(this)。super只能在子类的构造函数之中调用,须位于this之前。且子类的构造函数必须执行—次super函数。?
super作为对象时,在普通方法中,指向父类的原型对象。在静态方法中,指向父类。
//父类
class Person {
constructor(name, age){
this.name = name
this.age = age
}
sayHello(){
console.log('大家好')
}
}
//子类
class Chinese extends Person {
constructor(name, age, like){
super(name, age)
this.like = like
}
sayHi() {
super.sayHello()
console.log(`${this.name}${this.like}`)
}
}
const c1 = new Chinese('张三', 22,'eat')
c1.sayHi()
c1.sayHello()
//大家好
//张三eat
//大家好
cs