JavaScript: How can I assign a variable the same as another variable inside the same object?












-1















sorry if this is a duplicate, but I couldn't find any others.



So I tried doing this.



var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var player1 = {
width: 20,
height: 75,
x: canvas.width/6-player1.width/2,
y: canvas.height/2-player1.height/2,
speed: 5
};

function drawPlayer1() {
ctx.beginPath();
ctx.rect(player1.x, player1.y, player1.width, player1.height);
ctx.fillStyle = "#b10000";
ctx.fill();
ctx.closePath();
}

drawPlayer1();


But the problem is that I can't assign x to player1.width because width is assigned inside player1 where it's getting "used".



BTW I am doing this because of symmetry.



I could just have these variables for themselves, but I am trying to clean up my code.



So, how can I get around this problem by using objects?










share|improve this question



























    -1















    sorry if this is a duplicate, but I couldn't find any others.



    So I tried doing this.



    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var player1 = {
    width: 20,
    height: 75,
    x: canvas.width/6-player1.width/2,
    y: canvas.height/2-player1.height/2,
    speed: 5
    };

    function drawPlayer1() {
    ctx.beginPath();
    ctx.rect(player1.x, player1.y, player1.width, player1.height);
    ctx.fillStyle = "#b10000";
    ctx.fill();
    ctx.closePath();
    }

    drawPlayer1();


    But the problem is that I can't assign x to player1.width because width is assigned inside player1 where it's getting "used".



    BTW I am doing this because of symmetry.



    I could just have these variables for themselves, but I am trying to clean up my code.



    So, how can I get around this problem by using objects?










    share|improve this question

























      -1












      -1








      -1


      0






      sorry if this is a duplicate, but I couldn't find any others.



      So I tried doing this.



      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");

      var player1 = {
      width: 20,
      height: 75,
      x: canvas.width/6-player1.width/2,
      y: canvas.height/2-player1.height/2,
      speed: 5
      };

      function drawPlayer1() {
      ctx.beginPath();
      ctx.rect(player1.x, player1.y, player1.width, player1.height);
      ctx.fillStyle = "#b10000";
      ctx.fill();
      ctx.closePath();
      }

      drawPlayer1();


      But the problem is that I can't assign x to player1.width because width is assigned inside player1 where it's getting "used".



      BTW I am doing this because of symmetry.



      I could just have these variables for themselves, but I am trying to clean up my code.



      So, how can I get around this problem by using objects?










      share|improve this question














      sorry if this is a duplicate, but I couldn't find any others.



      So I tried doing this.



      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");

      var player1 = {
      width: 20,
      height: 75,
      x: canvas.width/6-player1.width/2,
      y: canvas.height/2-player1.height/2,
      speed: 5
      };

      function drawPlayer1() {
      ctx.beginPath();
      ctx.rect(player1.x, player1.y, player1.width, player1.height);
      ctx.fillStyle = "#b10000";
      ctx.fill();
      ctx.closePath();
      }

      drawPlayer1();


      But the problem is that I can't assign x to player1.width because width is assigned inside player1 where it's getting "used".



      BTW I am doing this because of symmetry.



      I could just have these variables for themselves, but I am trying to clean up my code.



      So, how can I get around this problem by using objects?







      javascript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 22:00









      BjølleBjølle

      33




      33
























          3 Answers
          3






          active

          oldest

          votes


















          0














          Since player1.width is not defined yet-- because you are still in the middle of defining player1-- you can define it and the other static properties first, and then assign the dynamic ones on the next line with Object.assign.



          var player1 = {
          width: 20,
          height: 75,
          speed: 5
          };
          Object.assign(player1, {
          x: canvas.width/6-player1.width/2,
          y: canvas.height/2-player1.height/2,
          });





          share|improve this answer































            4














            Consider using getters.






            var player1 = {
            width: 20,
            height: 75,
            get x() { return this.width + 10 },
            get y() { return this.height + 10 }
            };

            console.log(player1.x, player1.y);





            If you want the ability to set the value directly and override the formula, you could utilize setters too:






            var player1 = {
            width: 20,
            height: 75,
            _x: null,
            _y: null,

            get x() { return this._x || this.width + 10 },
            set x (newX) { this._x = newX },

            get y() { return this._y || this.height + 10 },
            set y (newY) { this._y = newY }
            };

            console.log(player1.x, player1.y);
            player1.x = 500;
            player1.y = 200;
            console.log(player1.x, player1.y);








            share|improve this answer


























            • I don't think that's what they're going for if x and y changes.

              – Jacque Goupil
              Nov 13 '18 at 22:06











            • @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

              – Tyler Roper
              Nov 13 '18 at 22:09



















            0














            You can't access player1 from within the definition of player1 because it doesn't exist yet. When the interpreter parses this code, it first creates an object out of the object literal, then it stores it in the player1 variable. And since player1 didn't exist beforehand, player1.width causes an error.



            // original code which doesn't work
            var player1 = {
            width: 20,
            height: 75,
            x: canvas.width/6-player1.width/2,
            y: canvas.height/2-player1.height/2,
            speed: 5
            };


            A simple way to fix it is to set those variables after creating the object.



            var player1 = { ... };

            player1.x = canvas.width/6 - player1.width/2;
            player1.y = canvas.height/2 - player1.height/2;


            Alternatively you could do this:



            Object.assign(player1, {
            x: canvas.width/6 - player1.width/2,
            y: canvas.height/2 - player1.height/2;
            });


            This code creates a new object with the x and y properties and then copies them to player1. But for just these two properties, I'd stick to the first solution, it's clearer and simpler.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290150%2fjavascript-how-can-i-assign-a-variable-the-same-as-another-variable-inside-the%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Since player1.width is not defined yet-- because you are still in the middle of defining player1-- you can define it and the other static properties first, and then assign the dynamic ones on the next line with Object.assign.



              var player1 = {
              width: 20,
              height: 75,
              speed: 5
              };
              Object.assign(player1, {
              x: canvas.width/6-player1.width/2,
              y: canvas.height/2-player1.height/2,
              });





              share|improve this answer




























                0














                Since player1.width is not defined yet-- because you are still in the middle of defining player1-- you can define it and the other static properties first, and then assign the dynamic ones on the next line with Object.assign.



                var player1 = {
                width: 20,
                height: 75,
                speed: 5
                };
                Object.assign(player1, {
                x: canvas.width/6-player1.width/2,
                y: canvas.height/2-player1.height/2,
                });





                share|improve this answer


























                  0












                  0








                  0







                  Since player1.width is not defined yet-- because you are still in the middle of defining player1-- you can define it and the other static properties first, and then assign the dynamic ones on the next line with Object.assign.



                  var player1 = {
                  width: 20,
                  height: 75,
                  speed: 5
                  };
                  Object.assign(player1, {
                  x: canvas.width/6-player1.width/2,
                  y: canvas.height/2-player1.height/2,
                  });





                  share|improve this answer













                  Since player1.width is not defined yet-- because you are still in the middle of defining player1-- you can define it and the other static properties first, and then assign the dynamic ones on the next line with Object.assign.



                  var player1 = {
                  width: 20,
                  height: 75,
                  speed: 5
                  };
                  Object.assign(player1, {
                  x: canvas.width/6-player1.width/2,
                  y: canvas.height/2-player1.height/2,
                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 '18 at 22:10









                  chiliNUTchiliNUT

                  12.5k84678




                  12.5k84678

























                      4














                      Consider using getters.






                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      If you want the ability to set the value directly and override the formula, you could utilize setters too:






                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);








                      share|improve this answer


























                      • I don't think that's what they're going for if x and y changes.

                        – Jacque Goupil
                        Nov 13 '18 at 22:06











                      • @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                        – Tyler Roper
                        Nov 13 '18 at 22:09
















                      4














                      Consider using getters.






                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      If you want the ability to set the value directly and override the formula, you could utilize setters too:






                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);








                      share|improve this answer


























                      • I don't think that's what they're going for if x and y changes.

                        – Jacque Goupil
                        Nov 13 '18 at 22:06











                      • @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                        – Tyler Roper
                        Nov 13 '18 at 22:09














                      4












                      4








                      4







                      Consider using getters.






                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      If you want the ability to set the value directly and override the formula, you could utilize setters too:






                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);








                      share|improve this answer















                      Consider using getters.






                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      If you want the ability to set the value directly and override the formula, you could utilize setters too:






                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);








                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      var player1 = {
                      width: 20,
                      height: 75,
                      get x() { return this.width + 10 },
                      get y() { return this.height + 10 }
                      };

                      console.log(player1.x, player1.y);





                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);





                      var player1 = {
                      width: 20,
                      height: 75,
                      _x: null,
                      _y: null,

                      get x() { return this._x || this.width + 10 },
                      set x (newX) { this._x = newX },

                      get y() { return this._y || this.height + 10 },
                      set y (newY) { this._y = newY }
                      };

                      console.log(player1.x, player1.y);
                      player1.x = 500;
                      player1.y = 200;
                      console.log(player1.x, player1.y);






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 13 '18 at 22:18

























                      answered Nov 13 '18 at 22:04









                      Tyler RoperTyler Roper

                      13.6k31841




                      13.6k31841













                      • I don't think that's what they're going for if x and y changes.

                        – Jacque Goupil
                        Nov 13 '18 at 22:06











                      • @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                        – Tyler Roper
                        Nov 13 '18 at 22:09



















                      • I don't think that's what they're going for if x and y changes.

                        – Jacque Goupil
                        Nov 13 '18 at 22:06











                      • @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                        – Tyler Roper
                        Nov 13 '18 at 22:09

















                      I don't think that's what they're going for if x and y changes.

                      – Jacque Goupil
                      Nov 13 '18 at 22:06





                      I don't think that's what they're going for if x and y changes.

                      – Jacque Goupil
                      Nov 13 '18 at 22:06













                      @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                      – Tyler Roper
                      Nov 13 '18 at 22:09





                      @JacqueGoupil You may be right. If OP is trying to preserve the ability to set x directly, that might make this a bit more intricate. I'll add an additional piece of code to account for that.

                      – Tyler Roper
                      Nov 13 '18 at 22:09











                      0














                      You can't access player1 from within the definition of player1 because it doesn't exist yet. When the interpreter parses this code, it first creates an object out of the object literal, then it stores it in the player1 variable. And since player1 didn't exist beforehand, player1.width causes an error.



                      // original code which doesn't work
                      var player1 = {
                      width: 20,
                      height: 75,
                      x: canvas.width/6-player1.width/2,
                      y: canvas.height/2-player1.height/2,
                      speed: 5
                      };


                      A simple way to fix it is to set those variables after creating the object.



                      var player1 = { ... };

                      player1.x = canvas.width/6 - player1.width/2;
                      player1.y = canvas.height/2 - player1.height/2;


                      Alternatively you could do this:



                      Object.assign(player1, {
                      x: canvas.width/6 - player1.width/2,
                      y: canvas.height/2 - player1.height/2;
                      });


                      This code creates a new object with the x and y properties and then copies them to player1. But for just these two properties, I'd stick to the first solution, it's clearer and simpler.






                      share|improve this answer




























                        0














                        You can't access player1 from within the definition of player1 because it doesn't exist yet. When the interpreter parses this code, it first creates an object out of the object literal, then it stores it in the player1 variable. And since player1 didn't exist beforehand, player1.width causes an error.



                        // original code which doesn't work
                        var player1 = {
                        width: 20,
                        height: 75,
                        x: canvas.width/6-player1.width/2,
                        y: canvas.height/2-player1.height/2,
                        speed: 5
                        };


                        A simple way to fix it is to set those variables after creating the object.



                        var player1 = { ... };

                        player1.x = canvas.width/6 - player1.width/2;
                        player1.y = canvas.height/2 - player1.height/2;


                        Alternatively you could do this:



                        Object.assign(player1, {
                        x: canvas.width/6 - player1.width/2,
                        y: canvas.height/2 - player1.height/2;
                        });


                        This code creates a new object with the x and y properties and then copies them to player1. But for just these two properties, I'd stick to the first solution, it's clearer and simpler.






                        share|improve this answer


























                          0












                          0








                          0







                          You can't access player1 from within the definition of player1 because it doesn't exist yet. When the interpreter parses this code, it first creates an object out of the object literal, then it stores it in the player1 variable. And since player1 didn't exist beforehand, player1.width causes an error.



                          // original code which doesn't work
                          var player1 = {
                          width: 20,
                          height: 75,
                          x: canvas.width/6-player1.width/2,
                          y: canvas.height/2-player1.height/2,
                          speed: 5
                          };


                          A simple way to fix it is to set those variables after creating the object.



                          var player1 = { ... };

                          player1.x = canvas.width/6 - player1.width/2;
                          player1.y = canvas.height/2 - player1.height/2;


                          Alternatively you could do this:



                          Object.assign(player1, {
                          x: canvas.width/6 - player1.width/2,
                          y: canvas.height/2 - player1.height/2;
                          });


                          This code creates a new object with the x and y properties and then copies them to player1. But for just these two properties, I'd stick to the first solution, it's clearer and simpler.






                          share|improve this answer













                          You can't access player1 from within the definition of player1 because it doesn't exist yet. When the interpreter parses this code, it first creates an object out of the object literal, then it stores it in the player1 variable. And since player1 didn't exist beforehand, player1.width causes an error.



                          // original code which doesn't work
                          var player1 = {
                          width: 20,
                          height: 75,
                          x: canvas.width/6-player1.width/2,
                          y: canvas.height/2-player1.height/2,
                          speed: 5
                          };


                          A simple way to fix it is to set those variables after creating the object.



                          var player1 = { ... };

                          player1.x = canvas.width/6 - player1.width/2;
                          player1.y = canvas.height/2 - player1.height/2;


                          Alternatively you could do this:



                          Object.assign(player1, {
                          x: canvas.width/6 - player1.width/2,
                          y: canvas.height/2 - player1.height/2;
                          });


                          This code creates a new object with the x and y properties and then copies them to player1. But for just these two properties, I'd stick to the first solution, it's clearer and simpler.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 13 '18 at 22:22









                          Jacque GoupilJacque Goupil

                          2,9201836




                          2,9201836






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290150%2fjavascript-how-can-i-assign-a-variable-the-same-as-another-variable-inside-the%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              List item for chat from Array inside array React Native

                              Thiostrepton

                              Caerphilly