Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 创建对象

作者:Xn﹏仍嘫佷痌   发布日期:2025-07-15   浏览:22

// 使用对象字面量创建对象
const person = {
  name: 'Alice',
  age: 25,
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

// 解释:这是最简单的方式,直接使用大括号包裹键值对来创建一个对象。
// 其中 `name` 和 `age` 是属性,`greet` 是方法。

// 使用构造函数创建对象
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
  };
}

const anotherPerson = new Person('Bob', 30);

// 解释:通过定义一个构造函数 `Person`,可以使用 `new` 关键字创建多个类似的对象实例。
// 构造函数中的 `this` 指向新创建的对象。

// 使用 Object.create 方法创建对象
const prototype = {
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const yetAnotherPerson = Object.create(prototype);
yetAnotherPerson.name = 'Charlie';
yetAnotherPerson.age = 35;

// 解释:`Object.create` 方法允许我们指定对象的原型。这里 `yetAnotherPerson` 继承了 `prototype` 对象的方法和属性。

以上是几种常见的在 JavaScript 中创建对象的方式及其解释。

上一篇:js 查看对象类型

下一篇:js 遍历 对象

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站