javascript 类中的一个附加类- JS

rqenqsqc  于 2023-06-28  发布在  Java
关注(0)|答案(3)|浏览(108)

我从一个项目的API中获得了这个类

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

我想在JS中重新创建这个类,以将新的信息推送到具有上述格式的数组中。
在互联网上的一些研究中,我找到了这样的解决方案:

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

但我不知道如何使用我的第一个构造函数(below):
我有这样的东西:

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

谢谢你的帮助

yjghlzjz

yjghlzjz1#

据我所知,你有一个ES6类,并试图用一些JSON数据示例化它。假设JSON数据是以数组的形式出现的,我想您可能希望JSON数组中的每一项都有多个classPicture示例。就像

// If it comes from your API as a string you can JSON.parse() it.
const data = [
  {
    "id": 1,
    "categoryId": 1,
    "userId": 1,
    "category": {
      "id": 1,
      "name": "Category one"
    }
  },
  {
    "id": 2,
    "categoryId": 2,
    "userId": 2,
    "category": {
      "id": 2,
      "name": "Category two"
    }
  }
];

作为第一步,我建议像这样分离两个类:

class ClassCategory {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }

    // Random method. You could just directly access the name in your case, but if you use public/private properties from ES2022 or typescript, you'd need to define getter and setter methods.
    getName() {
        return this.name;
    }
}

class ClassPicture {

  constructor(id, userId, category) {
    this.id = id;
    this.userId = userId;
    // Here category is actually the category object you create beforehand.
    this.category = category;
  }

  // Again a random method, just demonstrating how the class methods work.
  getCategoryName() {
        return this.category.getName();
    }
}

这里我去掉了categoryId属性,因为在category JSON对象中已经有了它。
最后,可以像这样示例化类

const pictures = [];

for(const picture of data) {
    // Instantiate the category, you can also do it in the line below like
    // const pictureInstance = new ClassPicture(picture.id, picture.userId, new ClassCategory(picture.category.id, picture.category.name));

    const category = new ClassCategory(picture.category.id, picture.category.name);
    const pictureInstance = new ClassPicture(picture.id, picture.userId, category)

    pictures.push(pictureInstance)
}

// Allows you to get the category name from the instance.
console.log(pictures[0].getCategoryName());

需要指出的是,javascript中的几乎所有内容都是对象,您可以简单地JSON.parse()您的数据并访问属性,如

console.log(data[0].category.name)

我不知道你的确切用例,但如果你不需要类附带的额外功能(例如:以特殊方式更改/获取数据的方法-考虑一个返回firstName + lastName的函数),您可以直接访问数据。

8cdiaqws

8cdiaqws2#

const category = class category {
      constructor(id, name) {
        this.id = id;
        this.name = name;
      }
    }

你不能在变量中声明一个类。做你想做的事的正确方法是:

class category {
      constructor(id, name) {
        this.id = id;
        this.name = name;
      }
}
class classPicture {
  constructor(id, categoryId, userId, category) {
    this.id = id;
    this.categoryId = categoryId;
    this.userId = userId;
    this.category = category  
    }
}
const newPictureAdded = new classPicture(
      1,
      2,
      JSON.parse(sessionStorage.getItem("id")),
      new category(2,1)
);

类只是一个结构。要实际使用它,您需要使用'new'关键字创建类的示例。

7eumitmz

7eumitmz3#

你不需要一个类来使用你的数据,直接使用它。

    • 但是**如果你需要你的后端数据作为一个类的示例,你可以这样做:
  • 获取JSON格式的后端数据
  • 使用JSON.parse解析它,并提供reviver函数作为第二个参数
  • 在Reviver中设置对象的原型
  • 结果,您将获得以类的示例形式呈现的数据,这些类具有这些类的所有方法和属性

例如:

const json = JSON.stringify([
    {
        "id": 1,
        "categoryId": 1,
        "userId": 1,
        "category": {
            "id": 1,
            "name": "Objets"
        }
    }
]);

// we extend our data with key property

class Picture {
    id
    categoryId
    userId
    category
    get key() {
        return `${this.id} ${this.categoryId} ${this.userId} ${this.category.key}`;
    }
};

class Category {
    id
    name
    get key() {
        return `${this.id} ${this.name}`;
    }
};

const data = JSON.parse(json, (key, val) => {
    if (val.categoryId) { // some code to determine a picture
        Object.setPrototypeOf(val, Picture.prototype);
    } else if (key === 'category') { // some code to determine a category
        Object.setPrototypeOf(val, Category.prototype);
    }
    return val;
});

const [picture] = data;

// print picture's category's key:
console.log(picture.category.key);

// print picture's key:
console.log(picture.key);

相关问题