调用Javascript函数时,如何设置自定义值“this”? [英] When calling a Javascript function, how do I set a custom value of "this"?
本文介绍了调用Javascript函数时,如何设置自定义值“this”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jQuery并且我有一个用作事件回调的函数,因此在该函数中this表示捕获事件的对象。但是,有一个实例,我想从另一个函数显式调用该函数 - 在这种情况下如何设置函数中的this将相等?
I'm using jQuery and I have a function that serves as an event callback, and so in that function "this" represents the object that that captured the event. However, there's an instance where I want to call the function explicitly from another function - how do I set what "this" will equal within the function in this case?
For示例:
function handleEvent(event) {
$(this).removeClass("sad").addClass("happy");
}
$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
handleEvent(e); // in this case, "this" will be the window object
// but I'd like to set it to be, say, the input in question
}
}
推荐答案
handleEvent.call(this, e);
这篇关于调用Javascript函数时,如何设置自定义值“this”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文