创建对象我怎样才能获得嵌套对象

时间:2021-05-02 07:44:45

标签: javascript object constructor nested

我正在创建一个构造函数。所以我需要让我的对象除了嵌套对象外一切都很好,我该怎么做?

function creation(name, value, id, name) {
  this.name = name;
  this.value = value;
  this.category = {
    id: "",
    name: ""
  }
}

let creationOne = new creation('book', 350, 1, "Something extraoridnary");
console.log(creationOne);

3 个答案:

答案 0 :(得分:0)

使用 ES6 对象属性值简写

  • 将第一个参数重命名为 bookName
  • 现在您可以为 id 对象内的 namecategory 属性赋值。
  • 因此,您可以执行以下任一操作:this.category = {id: id, name: name} OR 只需 this.category = {id, name}

function creation(bookName, value, id, name) {
  this.name = bookName;
  this.value = value;
  this.category = {id, name}
}

let creationOne = new creation('book', 350, 1, "Something extraoridnary");

console.log(creationOne);

答案 1 :(得分:0)

两个 name 参数需要不同的名称。然后在创建嵌套对象时需要使用参数变量。

function creation(object_name, value, id, category_name) {
  this.name = object_name;
  this.value = value;
  this.category = {
    id: id,
    name: category_name
  }
}

let creationOne = new creation('book', 350, 1, "Something extraoridnary");
console.log(creationOne);

答案 2 :(得分:0)

一种选择是将类别作为对象传入:

function creation(name, value, category) {
  this.name = name;
  this.value = value;
  this.category = category;
}

let creationOne = new creation('book', 350, { id: 1, name: "Something extraoridnary" });
console.log(creationOne);