Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jQuery的原型函数中使用它?_Javascript_Jquery_Oop - Fatal编程技术网

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

Javascript 如何在jQuery的原型函数中使用它?,javascript,jquery,oop,Javascript,Jquery,Oop,我正在尝试将一些JavaScript功能迁移到OOP JavaScript,如下所示: function Test(parameters) { this.containerID = parameters['containerID']; .... this.navNext = $('#' + this.containerID + ' #test'); ... } Test.prototype = { constructor: Test, ...

我正在尝试将一些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();
但是,当我单击next按钮或$'test\u id'test'元素时,我得到以下错误:

Uncaught ReferenceError: showNext is not defined 
我猜在on jQuery函数中this.showNext指向的是所选元素showNext函数,而不是我的原型函数

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

看看这是什么

当您在日志中查看它时,您将看到这是您单击的元素

范围是错误的,但你可以用

或者你可以使用

看看这是什么

当您在日志中查看它时,您将看到这是您单击的元素

范围是错误的,但你可以用

或者你可以使用

在事件处理程序中,这是指接收事件的元素。您可以改为对此目标进行外部引用

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

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

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

this.navNext.on('click', this, function (event) {
    ...
    event.data.showNext();
});
请注意,在更改此设置的版本中,仍然可以通过event.currentTarget获得对元素的引用。或者只使用event.data版本,这仍然是元素。

在事件处理程序中,这是指接收事件的元素。您可以改为对此目标进行外部引用

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

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

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

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

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

您可以只在“单击”处理程序中保存对对象的引用:


您只需在“单击”处理程序中保存对对象的引用:

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