js 实现 某人
JavaScript 实现人物对象
创建一个人物对象需要定义属性和方法,以下是一个基础的实现方式:

const person = {
name: 'John Doe',
age: 30,
gender: 'male',
occupation: 'developer',
greet() {
console.log(`Hello, my name is ${this.name}`);
},
introduce() {
console.log(`I'm ${this.age} years old and work as a ${this.occupation}`);
}
};
使用构造函数实现
如果需要创建多个人物实例,可以使用构造函数:

function Person(name, age, gender, occupation) {
this.name = name;
this.age = age;
this.gender = gender;
this.occupation = occupation;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
this.introduce = function() {
console.log(`I'm ${this.age} years old and work as a ${this.occupation}`);
};
}
const person1 = new Person('Jane Smith', 28, 'female', 'designer');
使用 ES6 类实现
更现代的实现方式是使用 ES6 类:
class Person {
constructor(name, age, gender, occupation) {
this.name = name;
this.age = age;
this.gender = gender;
this.occupation = occupation;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
introduce() {
console.log(`I'm ${this.age} years old and work as a ${this.occupation}`);
}
}
const person2 = new Person('Bob Johnson', 35, 'male', 'manager');
添加更多功能
可以扩展人物对象的功能:
class Person {
// ...之前的构造函数和方法
haveBirthday() {
this.age++;
console.log(`Happy birthday! Now I'm ${this.age} years old.`);
}
changeJob(newOccupation) {
this.occupation = newOccupation;
console.log(`I'm now working as a ${this.occupation}`);
}
}
使用场景示例
const person = new Person('Alice', 25, 'female', 'teacher');
person.greet(); // 输出: Hello, my name is Alice
person.introduce(); // 输出: I'm 25 years old and work as a teacher
person.haveBirthday(); // 输出: Happy birthday! Now I'm 26 years old
person.changeJob('professor'); // 输出: I'm now working as a professor






