使用代码举例js的几种继承方式
时间: 2023-06-03 17:08:11 浏览: 109
js继承实现示例代码
Sure, there are several ways to achieve inheritance in JavaScript:
1. Prototype Inheritance:
```js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
}
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const s = new Student('John', 18, 12);
s.greet(); // Output: Hi, my name is John and I am 18 years old.
```
2. Class Inheritance:
```js
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
}
const s = new Student('John', 18, 12);
s.greet(); // Output: Hi, my name is John and I am 18 years old.
```
3. Mixin Inheritance:
```js
const PersonMixin = {
greet() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
}
}
function Student(name, age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
Object.assign(Student.prototype, PersonMixin);
const s = new Student('John', 18, 12);
s.greet(); // Output: Hi, my name is John and I am 18 years old.
```
Hope this helps!
阅读全文