javascript创建一个student构造函数(具有姓名、年龄、班级等属性,和自我介绍方法),并使用构造函数创建对象(你自己的信息)
时间: 2024-01-06 17:04:47 浏览: 75
好的,以下是代码实现:
```javascript
// 定义 Student 构造函数
function Student(name, age, className) {
this.name = name;
this.age = age;
this.className = className;
// 自我介绍方法
this.introduce = function() {
console.log(`大家好,我是${this.className}班的${this.name},今年${this.age}岁。`);
}
}
// 使用构造函数创建对象
const myself = new Student('小明', 18, '一年级一班');
myself.introduce(); // 输出:大家好,我是一年级一班的小明,今年18岁。
```
以上代码中,我们定义了一个 `Student` 构造函数,它有三个属性:`name`、`age` 和 `className`,以及一个自我介绍方法 `introduce`。然后我们使用 `new` 关键字来创建了一个 `myself` 对象,它是一个 `Student` 类型的实例对象,然后调用 `introduce` 方法输出自我介绍。
相关问题
JacaScrip中编写一个Student构造函数,使其能够批量输出小明、小红等对象的属性和方法。 属性:name 、age 方法:sayHello(例如:你好,我叫小明)
可以参考下面的代码实现:
```javascript
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.sayHello = function() {
console.log("你好,我叫" + this.name);
}
var xiaoming = new Student("小明", 18);
var xiaohong = new Student("小红", 17);
console.log(xiaoming.name);
console.log(xiaoming.age);
xiaoming.sayHello();
console.log(xiaohong.name);
console.log(xiaohong.age);
xiaohong.sayHello();
```
运行代码后,输出结果如下:
```
小明
18
你好,我叫小明
小红
17
你好,我叫小红
```
可以看到,我们通过Student构造函数创建了两个实例对象xiaoming和xiaohong,并调用它们的属性和方法。
创建学生对象和教师对象并输出学生和教师相关信息(使用ES6新写法)
可以使用ES6中的class语法来创建学生和教师的对象。
下面是一个示例代码:
```javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`My name is ${this.name} and I'm ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
introduce() {
console.log(`I am a student. ${super.introduce()} My grade is ${this.grade}.`);
}
}
class Teacher extends Person {
constructor(name, age, subject) {
super(name, age);
this.subject = subject;
}
introduce() {
console.log(`I am a teacher. ${super.introduce()} My subject is ${this.subject}.`);
}
}
const student = new Student("Tom", 18, 12);
student.introduce(); // 输出:I am a student. My name is Tom and I'm 18 years old. My grade is 12.
const teacher = new Teacher("Alice", 35, "Math");
teacher.introduce(); // 输出:I am a teacher. My name is Alice and I'm 35 years old. My subject is Math.
```
在这个示例中,我们定义了一个`Person`类,它有一个构造函数和一个介绍方法。然后我们定义了一个`Student`类和一个`Teacher`类,它们都继承了`Person`类。`Student`类有一个额外的`grade`属性,`Teacher`类有一个额外的`subject`属性。它们都重写了`introduce()`方法,以输出与它们相关的信息。最后,我们创建了一个学生对象和一个教师对象,并调用它们的`introduce()`方法。