写一段js中的原型链代码
时间: 2024-05-12 20:21:17 浏览: 13
好的,以下是一段 JavaScript 中的原型链代码:
```
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
function Student(name, age, major) {
Person.call(this, name, age);
this.major = major;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.learn = function() {
console.log(`${this.name} is learning about ${this.major}.`);
}
const john = new Student('John', 20, 'Computer Science');
john.greet(); // 输出:Hello, my name is John and I am 20 years old.
john.learn(); // 输出:John is learning about Computer Science.
```
以上代码定义了两个构造函数:`Person` 和 `Student`。`Person` 构造函数有 `name` 和 `age` 属性,以及 `greet` 方法。`Student` 构造函数继承了 `Person` 构造函数,并新增了 `major` 属性和 `learn` 方法。`Object.create()` 方法被用来创建 `Student` 原型对象,该对象继承了 `Person` 原型对象。最后,通过 `new` 运算符创建一个 `john` 对象,并输出了 `greet` 和 `learn` 方法的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)