简体   繁体   中英

Can I assign 2 object for 1 definition in JavaScript?

For example, I have the following data

A : {  name: "Ball",
       color: { 
                out : ["red","black","green"],
                in : ["white","pink"]
               },
     }

I want to have another object to call with the same definition. Can I do this?

 A, B : {  name: "Ball",
           color: { 
                    out : ["red","black","green"],
                    in : ["white","pink"]
                   },
         }

If you're asking for the syntax to declare 2 fields with the same value, no you cannot do that. You can however declare a separate variable and point both fields at that variable.

const myBall = {
  name: "Ball",
  color: {
    out: ["red", "black", "green"],
    in: ["white", "pink"]
  }
};

const myObject = {
  A: myBall,
  B: myBall
};

or if you're looking to create two discrete objects, you could write a function to create a new one for you.

const createMyBall = () => ({
  name: "Ball",
  color: {
    out: ["red", "black", "green"],
    in: ["white", "pink"]
  }
});

const myObject = {
  A: createMyBall(),
  B: createMyBall()
};

assing to object

var a, b;
a = b =

 var a, b; a = b = { name: "Ball", color: { out: ["red","black","green"], in: ["white","pink"] }, }; console.log(a); console.log(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM