在 ECMAScript(ES6)中,引入了 class 关键字,使得 JavaScript 中的类和继承更加直观和易于理解。以下是关于 ES6 类和继承的一些基本概念:
类是一种用于创建对象的蓝图或模板。在 ES6 中,可以使用 class 关键字定义一个类:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
在这个例子中,我们定义了一个名为 Person 的类,它有一个构造函数 constructor 和一个方法 greet。
继承允许一个类从另一个类继承属性和方法。在 ES6 中,可以使用 extends 关键字实现继承:
class Employee extends Person {
constructor(name, age, salary) {
super(name, age); // 调用父类的构造函数
this.salary = salary;
}
introduce() {
super.greet(); // 调用父类的方法
console.log(`My salary is ${this.salary}.`);
}
}
在这个例子中,我们定义了一个名为 Employee 的类,它继承了 Person 类。Employee 类有一个额外的属性 salary 和一个额外的方法 introduce。我们使用 super 关键字调用父类的构造函数和方法。
现在我们可以创建 Person 和 Employee 类的实例,并使用它们的方法:
const person = new Person('Alice', 30);
person.greet(); // 输出: Hello, my name is Alice and I am 30 years old.
const employee = new Employee('Bob', 25, 5000);
employee.greet(); // 输出: Hello, my name is Bob and I am 25 years old.
employee.introduce(); // 输出: Hello, my name is Bob and I am 25 years old. My salary is 5000.
总之,ES6 中的类和继承提供了一种更加直观和易于理解的方式来创建和管理对象及其关系。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。