一个重要的问题是您必须将传递的 jQuery 对象/元素分配给一个this.element
- 或另一个this.propertyName
- 以便您稍后可以在实例的方法中访问它。
您也不能像那样直接调用MoveRight()
/MoveLeft()
因为这些函数不是在作用域链中定义的,而是在实例构造函数的原型中定义的,因此您需要引用实例本身来调用这些函数。
更新和注释代码如下:
(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 实现之前没有),也没有方法(根据定义,它们专门与类相关联),而是提供类似于类的甜美语法的构造函数。这是 TJ Crowder 写的一篇关于 JS 的“假”方法的很棒的文章,它有点高级,但每个人都应该能够从阅读中学到新的东西:http:
//blog.niftysnippets.org/2008/03/mythical-methods .html