如何在jQuery的原型函数中使用它

How to use this in prototype function with jQuery?

本文关键字:函数 原型 jQuery      更新时间:2023-09-26

我正在尝试将一些JavaScript功能迁移到OOP JavaScript,如下所示:

function Test(parameters) {
    this.containerID = parameters['containerID'];
    ....
    this.navNext = $('#' + this.containerID + ' #test');
    ...
}
Test.prototype = {
    constructor: Test,
    ...
    init: function () {
        ...
        this.navNext.on('click', function (event) {
            ...
            this.showNext(); //here is the issue
        });
       ...
    },
    showNext: function () {
        ...
    }  
};

然后我实例化如下的新实例:

test = new Test({'containerID':'test_id'});
test.init();

但当我点击"下一个按钮"或($('#test_id '#test'元素)时,我会收到以下错误:

Uncaught ReferenceError: showNext is not defined 

我猜在onjQuery函数中,this.showNext()指向的是所选元素showNext()函数,而不是我的原型函数。

有人能给我一个如何纠正这种行为的建议吗?

在事件处理程序中,this指的是接收事件的元素。相反,您可以对所需的this进行外部引用。

var that = this;
this.navNext.on('click', function (event) {
    ...
    that.showNext();
});

或者使用Function.prototype.bind(),它可以在较旧的浏览器中填充。

this.navNext.on('click', function (event) {
    ...
    this.showNext();
}.bind(this));

$proxy

this.navNext.on('click', $.proxy(function (event) {
    ...
    this.showNext();
}, this));

或者将对象作为事件数据传递。

this.navNext.on('click', this, function (event) {
    ...
    event.data.showNext();
});

请注意,在更改this的版本中,您仍然可以通过event.currentTarget获得对元素的引用。或者只使用event.data版本,this仍然是元素。

看看this是什么

this.navNext.on('click', function (event) {
    console.log(this);
    this.showNext(); //here is the issue
});

当你在日志中查看它时,你会发现"this"就是你点击的元素

作用域错误,但您可以使用jQuery的proxy()进行修复

this.navNext.on('click', $.proxy(this.showNext,this));

或者您可以使用Function.prototype.bind()

this.navNext.on('click', this.showNext.bind(this));

您只需在on('click'处理程序中保存对对象的引用:

   var thisRef = this;
    this.navNext.on('click', function (event) {
        ...
        thisRef.showNext(); //here is the issue
    });