返回
ES6之类与继承--详解
前端
2023-11-14 17:15:42
ES6之类与继承详解
类的声明与实例化
在ES6中,类通过class声明。类的声明一般有两种方式:
- 类表达式:
const Person = class {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
- 类声明:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
类实例化时,可以使用new关键字。例如:
const person = new Person('John Doe');
person.greet(); // 输出:Hello, my name is John Doe
继承
实现继承的方式主要有两种:
- 原型继承:
原型继承是通过修改对象的原型链来实现继承。例如:
const Parent = {
name: 'John Doe',
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
const Child = Object.create(Parent);
Child.name = 'Jane Doe';
Child.greet(); // 输出:Hello, my name is Jane Doe
- 类继承:
类继承是通过extends关键字来实现继承。例如:
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
class Child extends Parent {
constructor(name) {
super(name); // 调用父类的构造函数
}
}
const child = new Child('Jane Doe');
child.greet(); // 输出:Hello, my name is Jane Doe
先看个了例子
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
class Child1 extends Parent {
constructor(name) {
super(name);
}
}
class Child2 extends Parent {
constructor(name) {
super(name);
}
greet() {
super.greet();
console.log(`I am a child of ${this.name}`);
}
}
const child1 = new Child1('John Doe');
child1.greet(); // 输出:Hello, my name is John Doe
const child2 = new Child2('Jane Doe');
child2.greet(); // 输出:Hello, my name is Jane Doe
// I am a child of Jane Doe
输出结果
Hello, my name is John Doe
Hello, my name is Jane Doe
I am a child of Jane Doe
可以看到,生成Child1里面有了父级的属性name,实现了继承。为什么就实现继承了呢?
继承的实现原理
在JavaScript中,类继承是通过原型链实现的。当子类继承父类时,子类的原型对象会被设置为父类的实例。这意味着子类可以访问父类的所有属性和方法。
在上面的例子中,Child1和Child2都继承了Parent类。因此,Child1和Child2都可以访问Parent类的name属性和greet()方法。
结论
ES6中的类和继承为JavaScript带来了一种新的编程范式。类和继承可以帮助我们更轻松地编写出可维护性和可扩展性更高的代码。
希望这篇文章对您有所帮助。如果您有任何问题,请随时留言。