Javascript 访问方法时出现问题

Javascript 访问方法时出现问题,javascript,jquery,object,this,Javascript,Jquery,Object,This,我开始使用jquery和Model-View-ViewModel,在使用事件处理程序附件时遇到了一个问题:on()。 我的第一堂课是TictaToeModel,它在内存中操纵TictaToe游戏: var TicTacToeModel = function () { Observable.call(this); this.grid = new Array(3); for (let i = 0; i < this.grid.length; ++

我开始使用jquery和Model-View-ViewModel,在使用事件处理程序附件时遇到了一个问题:on()。 我的第一堂课是TictaToeModel,它在内存中操纵TictaToe游戏:

var TicTacToeModel = function () {
        Observable.call(this);
        this.grid = new Array(3);
        for (let i = 0; i < this.grid.length; ++i) {
            this.grid[i] = new Array(3);
        }
    };
//Some prototype function
//...
(游戏宣言:
game=new TicTacToeModel();

在我的第二节课中,我有一个函数:

TicTacToeController.prototype.addListeners = function() {
    this._model.on('change', this.render, this);
    this._model.play(0,0);//works
    this._element.on('click', "td", function() {
        this._model.play(0,0);//doesn't work
    });
};
当我在图形界面中单击单元格时,我想调用单元格(0,0)中的play()函数(函数play更新内存中的游戏),但我无法在.on()中执行。但是这似乎是在.on()函数之外工作的,所以我认为是
这个
使用不当造成了问题。

您需要这样使用

更改此项:

this._element.on('click', "td", function() {
    this._model.play(0,0);//doesn't work
});
致:


您不在同一范围内,它与调用play方法时使用的这个变量不同。 一个肮脏的解决办法可能是

let _model = this._model
this._element.on('click', "td", function() {
        _model.play(0,0);//work!
    });
但正如所说,这是一个肮脏的解决办法,也许其他人可以解释,但基本上认为这会产生内存泄漏。也许解决方案是在同一个类中使用一个方法,并将实例传递给click方法,类似于:

TicTacToeController.prototype.click = function() ...
...
this._element.on('click', "td", this.click);

我认为这应该可以解决问题,但我必须承认我不是js专家。

谢谢你的回答,这很好,但是如果我像这样在函数中添加一些jquery:
TicTacToeController.prototype.addListeners=function(){this.\u model.on('change',this.render,this);this.\u element.on('click','td',function()){$(this.addClass(“case”);$(this.html(“X”);this._model.play(0,0);//不起作用}.bind(this));};
没有考虑jquery,你有没有想法修复它?不确定“没有考虑jquery”是什么意思,但是你尝试过
$(这个._元素)…
而不是
$(this)…
$(this.\u元素)
不起作用,因为它改变了我的整个网格,但是如果我在:
this.\u元素中添加参数“event”。on('click',td',function(event){…}
,event.target起作用。但是为什么我不能使用
$(this)
,而它代表.on()的“td”元素呢功能?我也想过使用这个肮脏的变通方法,但我知道有更好的方法来解决我的问题^^。
let _model = this._model
this._element.on('click', "td", function() {
        _model.play(0,0);//work!
    });
TicTacToeController.prototype.click = function() ...
...
this._element.on('click', "td", this.click);