JavaScript的写类方式(6)

时间:2023-08-21 22:31:11
JavaScript的写类方式(6)

时间到了2015年6月18日,ES6正式发布了,到了ES6,前面的各种模拟类写法都可以丢掉了,它带来了关键字 class,extends,super。

ES6的写类方式

// 定义类 Person
class Person { constructor(name, age) {
this.name = name;
this.age = age;
} setName(name) {
this.name = name;
} getName() {
return this.name;
} toString() {
return 'name: ' + this.name + ', age: ' + this.age;
} } // 创建实例对象
var p = new Person('Backus', 35);
p instanceof Person; // true

以上定义了一个类,constructor 是构造器,这点和 Java 不同,Java的构造器名和类名相同。

和 Java 多象啊,再看看继承

class Man extends Person {
constructor(name, age, school) {
super(name, age); // 调用父类构造器
this.school = school;
} setSchool(school) {
this.school = school;
} getSchool() {
return this.school;
} toString() {
return super.toString() + ', school:' + this.school; // 调用父类的toString()
}
} var man = new Man('张三', '30', '光明中学');
man instanceof Man; // true
man instanceof Person; // true
console.log(man);

以上代码中,constructor 和 toString 方法中,都出现了 super 关键字,它指代父类的实例(即父类的 this 对象)。 之前 ES5 有个 Object.getPrototypeOf 来获取父类的原型对象

可以继续阅读:

JavaScript继承方式(1)