You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript重构API返回格式的类并正确实例化?

问题:创建对应API数据结构的JavaScript类并正确实例化

我从API获取到如下格式的数据结构:

[
  {
    "id": 1,
    "categoryId": 1,
    "userId": 1,
    "category": {
      "id": 1,
      "name": "Objets"
    }
  }
]

我想在JavaScript中创建对应的类,用来向数组中添加符合该格式的新数据。我尝试了一种写法,但不知道怎么正确调用构造函数实例化对象。

我的错误类写法:

export class classPicture {
  constructor(id, categoryId, userId, category) {
    this.id = id;
    this.categoryId = categoryId;
    this.userId = userId;
    const category = class category {
      constructor(id, name) {
        this.id = id;
        this.name = name;
      }
    }
  }
}

我的错误实例化代码:

const newPictureAdded = new classPicture(
      1,
      2,
      JSON.parse(sessionStorage.getItem("id"));
      category(2,1)
    );

问题分析

你当前的写法存在几个关键问题:

  • 在classPicture构造函数内部定义的category类,作用域仅限构造函数内部,外部无法调用category()创建实例
  • 实例化代码的参数列表里多了分号,属于语法错误
  • 没有将category实例正确赋值给classPicture的category属性

正确实现方案

方案1:单独定义Category类(推荐)

将Category类单独定义,符合模块化思想,也方便复用:

// 定义Category类(类名首字母大写,遵循JavaScript命名规范)
export class Category {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}

// 定义Picture类
export class Picture {
  constructor(id, categoryId, userId, category) {
    this.id = id;
    this.categoryId = categoryId;
    this.userId = userId;
    // 把传入的Category实例赋值给当前对象的category属性
    this.category = category;
  }
}

正确实例化方式

// 1. 创建Category实例
const targetCategory = new Category(2, "Objets");
// 2. 从sessionStorage获取userId
const userId = JSON.parse(sessionStorage.getItem("id"));
// 3. 创建Picture实例
const newPictureAdded = new Picture(1, 2, userId, targetCategory);

方案2:在Picture类内部直接组装category对象

如果不需要单独复用Category类,可以直接在构造函数中接收category的id和name,内部组装成对应结构:

export class Picture {
  constructor(id, categoryId, userId, categoryIdVal, categoryName) {
    this.id = id;
    this.categoryId = categoryId;
    this.userId = userId;
    // 直接在内部构造category对象
    this.category = {
      id: categoryIdVal,
      name: categoryName
    };
  }
}

// 实例化
const userId = JSON.parse(sessionStorage.getItem("id"));
const newPictureAdded = new Picture(1, 2, userId, 2, "Objets");

方案3:直接传入category对象参数

这种方式更灵活,允许直接传入符合结构的category对象:

export class Picture {
  constructor(id, categoryId, userId, category) {
    this.id = id;
    this.categoryId = categoryId;
    this.userId = userId;
    // 可以添加简单校验,确保category包含必要属性
    this.category = {
      id: category.id,
      name: category.name
    };
    // 或者直接展开对象:this.category = { ...category };
  }
}

// 实例化
const userId = JSON.parse(sessionStorage.getItem("id"));
const newPictureAdded = new Picture(1, 2, userId, { id: 2, name: "Objets" });

内容的提问来源于stack exchange,提问作者Noc er Gal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:43:18