<分区>
我是 JS 的新手,我知道函数是声明“类类”结构的方式。 我正在尝试做这样的事情:
function Game() {
// Class stuff
this.handleClick = function(e) {
alert(e);
}
// Bind event to method previously defined
$('#board').bind('click', function(e) {
this.handleClick(e); // <--- THIS IS THE PROBLEMATIC LINE
});
}
现在,如果在“有问题的行”我写:
handleClick(e)
我得到 Uncaught ReferenceError: handleClick is not defined
.
相反,如果我写:
this.handleClick(e);
我得到 Uncaught TypeError: Object #<HTMLCanvasElement> has no method 'handleClick'
但是,如果我这样做:
function Game() {
// Class stuff
this.handleClick = function(e) {
alert(e);
}
var game = this; // <--- I ASSIGN this TO board
// Bind event to method previously defined
$('#board').bind('click', function(e) {
game.handleClick(e); // <--- THIS WORKS!! WHY????
});
}
有效!?!?!
我的问题是:
- 为什么会这样?我知道
this
可能会有问题,但为什么将它分配给一个变量会改变它呢? - 我做错了吗?有没有更好的方法以更优雅的方式实现这样的目标?