How do I create a class in Javascript?

前端 未结 3 1531
無奈伤痛
無奈伤痛 2021-02-03 14:36

This is what I got so far, and it\'s not working at all :( all the variables are null in my player class and update never gets called.

I mean a programming class, not a

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-03 14:47

    The var makes a private variable, do prefix with this instead in your constructor:

            function Player () {
                this.speed = 5;
                this.x = 50;
                this.y = 50;
                var pri = 'private';
                this.update = function() {
                      if(keys[37]) this.x -= this.speed;
                      if(keys[39]) this.x += this.speed;
                }
            }
    
            var player = new Player;
            alert( player.speed ) // should alert 5
            alert( player.pri ) // should fail or say undefined
    

    You can also do...

          var player = {
               speed: 5,
               x:50,
               y:50,
               update: function() {
                   // code
               }
          }
    

    And then get rid of new Player and the Player constructor.

提交回复
热议问题