当前位置:首页 > JavaScript

js 实现 某人

2026-04-05 11:26:08JavaScript

JavaScript 实现人物对象

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

js 实现 某人

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}`);
  }
};

使用构造函数实现

如果需要创建多个人物实例,可以使用构造函数:

js 实现 某人

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

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…