class 继承
class 是 ES6 的新特性,也引入了 extends 关键字,在写法上确实更加容易接受,对于学过 Java 的人来说极易上手。如果你是第一次接触 class,这里建议先去百度一下 class 的定义和基本使用原则,现在我就当你们都学过 class 咯
/* class 语法格式:
class ClassName {
constructor() { ... }
method_name1() { ... }
method_name2() { ... }
}
注意:class 不是对象,而是对象的模板!
继承 语法格式:
class son extends father{
constructor() { ... }
method_name3() { ... }
} */
//测试案例,还是最开始的 example
'use strict'
class Person {
//使用 class 的时候,实例的属性必须定义在类的构造函数里,注意是实例属性,不是静态之类的
constructor(name) {
this.name = name;
}
//父类方法,不需要使用 function 关键字哦
eat() {
console.log(this.name + " 在吃饭");
}
}
//编写子类,继承父类
class College_student extends Person {
constructor(name, age) {
//使用 super 调用父类的构造函数,是不是和 Java 类似
super(name);
this.age = age;
}
//子类方法
run() {
console.log(this.name + " 在跑步");
}
}
//创建实例
let Mike = new College_student("Mike", 21);
Mike.eat(); //输出 Mike 在吃饭
Mike.run(); //输出 Mike 在跑步
这种方式是不是看起来就清楚很多了!我们顺便看一下继承关系,可以看到 Mike 的原型就是 Person,Person 的原型就是 Object,Object 的原型还是 Object(箭头可以无限点下去):
以上就是最基本的有关 JavaScript class 继承的语法格式,下面我补充一些关于 class 的知识点:
- 静态属性:只能通过类或者静态方法来访问的属性,使用 static 修饰
- 静态方法:只能通过类来访问的方法,可以访问类中的静态属性,使用 static 修饰
- 公有属性:可以直接使用类实例访问
- 私有属性:不可以使用类实例访问,只能通过类方法访问,用 # 修饰
class Test {
variable_1 = 10; //带初值的公有属性,前面不要手贱写 let 或者 var
variable_2; //不带初值的私有属性
#variable_3 = 20; //带初值的私有属性,前面使用 # 代表私有
#variable_4; //不带初值的私有属性
constructor(value_1, value_2, value_3, value_4) {
//这里我们将所有的属性都重新赋值,只需要注意私有属性在赋值的时候也需要带上 #
this.variable_1 = value_1;
this.variable_2 = value_2;
this.#variable_3 = value_3;
this.#variable_4 = value_4;
}
//静态属性,使用 static 修饰
static variable_5 = "Hello World";
//静态方法,使用 static 修饰
static getVariable_5() {
return this.variable_5;
}
/*这里我们想要获取私有属性,只能通过类中的方法。如果学习过 Java,完全按照 Java 中 get() 和 set() 的写法就行。get() 用于获取私有属性,set() 用于设置私有属性的值 */
getVariable_3() {
return this.#variable_3;
}
getVariable_4() {
return this.#variable_4;
}
}
//创建类实例
let test = new Test(10, 20, 30, 40);
//1、公有属性直接通过类实例获取
console.log("variable_1 = " + test.variable_1);
console.log("variable_2 = " + test.variable_2);
//2、私有属性通过类的 get() 方法获取
console.log("variable_3 = " + test.getVariable_3());
console.log("variable_4 = " + test.getVariable_4());
//3、静态属性通过类名访问
console.log("(Use class, not an instance)variable_5 = " + Test.variable_5);
//4、静态属性通过类静态方法访问
console.log("(Use static function)variable_5 = " + Test.getVariable_5());
控制台输出结果:
那么关于 JavaScript class 继承就写这么多吧。class 确实好用,但是不是所有的主流浏览器都支持 ES6 的 class,所以使用还需多加注意啊,不得已还是得使用 prototype!