当前位置:首页 > 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实现轮播

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

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现列表

js实现列表

使用 JavaScript 实现列表 JavaScript 提供了多种方式来实现列表功能,包括数组操作、DOM 元素动态生成等。以下是几种常见的实现方法: 使用数组存储列表数据 数组是 JavaSc…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…