jquery在处理事件时更改运算符“this”的行为吗?
问题描述:
请考虑以下课程。我开始使用JQuery。jquery在处理事件时更改运算符“this”的行为吗?
function AutoHide(elemControl, elemContent) {
this.elemControl = elemControl;
this.elemContent = elemContent;
this.delay = 500;
this.duration = 500;
this.direction = 'vertical';
this.effect = 'blind';
function softHide() {
if ($(this.elemContent).is(':visible')) {
$(this.elemContent).delay(this.delay);
$(this.elemContent).hide(this.effect, {direction: this.direction}, this.duration);
}
return this;
};
function softShow() {
if ($(this.elemContent).is(':hidden'))
$(this.elemContent).show(this.effect, {direction: this.direction}, this.duration);
return this;
};
function setClickControl() {
alert(this.elemControl);
$(this.elemControl).click(softToggleVisibility);
};
this.softHide = softHide;
this.softShow = softShow;
this.setClickControl = setClickControl;
};
我有自动隐藏对象的全局实例,以及方法softShow()和softHide()的工作就像一个魅力(谷歌通过Chrome浏览器的控制台)。但是,当我尝试运行setClickControl()方法时,我意识到运算符“this”引用HTMLElement,而不是类本身。这是正常的吗?我习惯于能够考虑运营商“this”对象的引用i
答
你是对的。正常的“this”对象的隐藏是首次使用jQuery时引起很多混淆的原因。如果你真的需要让“这一”行动你习惯的方式,使用jQuery的代理()API函数:
+0
谢谢,它的工作原理! – LRMAAX 2011-04-03 16:22:24
我提出了三种方法来操纵'在这个this'指针[问题](http://stackoverflow.com/questions/3349380/jquery-proxy-usage/3349438#3349438) - 在闭包中捕获'this',通过'jQuery.proxy'和函数的新'bind'方法在ES3中。所有这些技术的基本方法都是相同的 - 在闭包中捕获“this”并稍后参考它。 jQuery的'.proxy'和Function原型的'.bind'只是方便的包装器。 – Anurag 2011-04-03 05:57:02
你可以添加一个如何调用成员函数的例子吗? – Eric 2011-04-03 08:33:23