用js原型模式创建一个对象,编写三段代码
时间: 2024-05-16 14:13:40 浏览: 102
代码1:创建一个名为Person的构造函数,包含name和age属性和一个greet方法。
```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.`);
};
```
代码2:创建一个名为Student的构造函数,它继承自Person,包含一个major属性和一个study方法。
```javascript
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.study = function() {
console.log(`I am studying ${this.major}.`);
};
```
代码3:创建一个Person和Student对象并调用它们的方法。
```javascript
const person = new Person('John', 30);
person.greet(); // 输出:Hello, my name is John and I am 30 years old.
const student = new Student('Jane', 20, 'Computer Science');
student.greet(); // 输出:Hello, my name is Jane and I am 20 years old.
student.study(); // 输出:I am studying Computer Science.
```
阅读全文