如何在jQuery的原型函数中使用它
How to use this in prototype function with jQuery?
我正在尝试将一些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
我猜在on
jQuery函数中,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
});
相关文章:
- 创建对象函数原型和代码是错误的
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- 使用构造函数 - 原型从文本框输出值
- 为什么函数对象的实例没有继承函数原型属性
- 获取函数原型的源代码
- 挂钩文档.使用函数原型创建元素
- 理解函数原型和__proto__
- 在Javascript的函数原型中创建函数
- Emberjs :哈希中的函数原型
- Javascript函数在父函数原型中带有原型
- 构造函数原型-继承混淆
- 本地作用域函数原型覆盖
- 使用函数原型的 JavaScript 继承问题
- 为什么我的代码认为 canvas 函数在 JavaScript 中的构造函数原型中是未定义的
- 所有内容也都链接到函数原型
- Javascript MDN 函数原型绑定 polyfill 在数组中是可枚举的
- Javascript将对象传递给函数原型
- 我应该使用构造函数/原型吗?
- 为什么函数原型不能修改 .
- 删除函数原型对象