使用jQuery创建一个简单的JavaScript类 [英] Creating a simple JavaScript class with jQuery

查看:95
本文介绍了使用jQuery创建一个简单的JavaScript类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解jQuery类,但它不是很顺利。

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 player = new Player($("playerElement"));
player.InitEvents();

使用其他人的例子,这就是我的尝试:

Using other people's examples, this is what I tried:

$.Player = function ($) {

};

$.Player.prototype.InitEvents = function () {

    $(this).keypress(function (e) {
        var key = e.which;
        if (key == 100) {
            MoveRight();
        }
        if (key == 97) {
            MoveLeft();
        }
    });
};

$.Player.prototype.MoveRight = function () {
    $(this).css("right", this.playerX += 10);
}

$.Player.prototype.MoveLeft = function () {
    $(this).css("right", this.playerX -= 10);
}

$.Player.defaultOptions = {
    playerX: 0,
    playerY: 0
};

最终目标是让一个角色在屏幕上左右移动,使用键盘字母 A D

The end goal is to have a character moving on the screen left and right using the keyboard letters A and D.

我有一种感觉,我'我对这个班级做了一些非常错误的事情
,但我不确定原因。

I have a feeling that I'm doing something very wrong with this "class" but I'm not sure why.

(对不起我的英文)

推荐答案

一个重要的问题是你必须将传递的jQuery对象/元素分配给 this.element - 或另一个 this.propertyName - 所以你可以稍后在实例的方法中访问它。

An important issue is that you have to assign the passed jQuery object/element to a this.element - or another this.propertyName - so you can access it later inside the instance's methods.

你也不能直接调用 MoveRight() / MoveLeft(),因为这些函数未在作用域链中定义,但是而是在实例的构造函数的原型中,因此您需要对实例本身的引用来调用它们。

You also cannot call MoveRight()/MoveLeft() directly like that because those functions are not defined up in the scope chain, but rather in the prototype of your instance's Constructor, hence you need a reference to the instance itself to call these.

以下更新和注释的代码:

Updated and commented code below:

(function ($) { //an IIFE so safely alias jQuery to $
    $.Player = function (element) { //renamed arg for readability

        //stores the passed element as a property of the created instance.
        //This way we can access it later
        this.element = (element instanceof $) ? element : $(element);
        //instanceof is an extremely simple method to handle passed jQuery objects,
        //DOM elements and selector strings.
        //This one doesn't check if the passed element is valid
        //nor if a passed selector string matches any elements.
    };

    //assigning an object literal to the prototype is a shorter syntax
    //than assigning one property at a time
    $.Player.prototype = {
        InitEvents: function () {
            //`this` references the instance object inside of an instace's method,
            //however `this` is set to reference a DOM element inside jQuery event
            //handler functions' scope. So we take advantage of JS's lexical scope
            //and assign the `this` reference to another variable that we can access
            //inside the jQuery handlers
            var that = this;
            //I'm using `document` instead of `this` so it will catch arrow keys
            //on the whole document and not just when the element is focused.
            //Also, Firefox doesn't fire the keypress event for non-printable
            //characters so we use a keydown handler
            $(document).keydown(function (e) {
                var key = e.which;
                if (key == 39) {
                    that.moveRight();
                } else if (key == 37) {
                    that.moveLeft();
                }
            });

            this.element.css({
                //either absolute or relative position is necessary 
                //for the `left` property to have effect
                position: 'absolute',
                left: $.Player.defaultOptions.playerX
            });
        },
        //renamed your method to start with lowercase, convention is to use
        //Capitalized names for instanceables only
        moveRight: function () {
            this.element.css("left", '+=' + 10);
        },
        moveLeft: function () {
            this.element.css("left", '-=' + 10);
        }
    };


    $.Player.defaultOptions = {
        playerX: 0,
        playerY: 0
    };

}(jQuery));

//so you can use it as:
var player = new $.Player($("#playerElement"));
player.InitEvents();

小提琴

另请注意,JavaScript没有实际的类(至少在ES6实现之前),也没有方法(通过定义只与Classes相关联,而是与构造函数相关联,它提供类似于类的甜蜜语法。这是一篇由TJ Crowder撰写的关于JS假方法的精彩文章,它有点先进,但每个人都应该能够通过阅读来学习新东西:

http://blog.niftysnippets.org/2008/03/mythical-methods.html

Also note that JavaScript does not have actual "classes" (at least not until ES6 gets implemented) nor Methods (which by definition are associated exclusively to Classes), but rather Constructors which provide a sweet syntax that resembles classes. Here's an awesome article written by TJ Crowder regarding JS's "fake" methods, it is a little advanced but everyone should be able to learn something new from reading it:
http://blog.niftysnippets.org/2008/03/mythical-methods.html

这篇关于使用jQuery创建一个简单的JavaScript类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆