Creating a simple JavaScript class with jQuery

后端 未结 2 1861
天命终不由人
天命终不由人 2021-01-31 00:41

I\'m trying to understand jQuery classes but it is not going very well.

My goal is to use a class this way (or to learn a better way to do it):

var playe         


        
2条回答
  •  孤城傲影
    2021-01-31 01:30

    When you use this inside your Player prototype functions, this points to the current Player object.

    But when you use $(this).keypress it requires that this points to an HTML element.

    The two simply are incompatible. There is only one this and it points to the current Player object, not to an HTML element.

    To fix your problem, you will need to pass the HTML element into the Player object upon its creation or into the relevant function calls.

    You can pass the element into the Player object upon construction like this:

    $.Player = function ($, element) {
            this.element = element;
    
    };
    
    $.Player.prototype.InitEvents = function () {
    
        $(this.element).keypress(function (e) {
            var key = e.which;
            if (key == 100) {
                MoveRight();
            }
            if (key == 97) {
                MoveLeft();
            }
        });
     };
    
     $.Player.prototype.MoveRight = function () {
         $(this.element).css("right", this.playerX += 10);
     }
    
     $.Player.prototype.MoveLeft = function () {
         $(this.element).css("right", this.playerX -= 10);
     }
    
    $.Player.defaultOptions = {
        playerX: 0,
        playerY: 0
    };
    

提交回复
热议问题