当函数和选择器不在一起时,使用“this”
有了这个
例1
$("#my_div").on("click", function () { alert( $(this).attr("id") ) });
我们获得了正确的结果,但如果我使用这个:
例2
function thisId () { alert( $(this).attr("id") ) } $("#my_div").on("click", function () { thisId(); });
现在结果未定义。 当使用this
的选择器和函数被写成不同的表达式时,请告诉我如何使用this
,如例2中所示 ?
要使jQuery将元素引用传递给函数,您必须提供函数作为引用。 试试这个:
$("#my_div").on("click", thisId);
@bot的更新
function thisId (event) { alert( $(this).attr("id") ) alert(event.type); } $("#my_div").on("click", thisId);
@ RoryMcCrossan的答案是正确的,这就是为什么:JS确定this
ad hoc引用的内容,即:当调用函数时,它会查看调用上下文:
myObject.property = function(){console.log(this)} myObject.property(); /\ || ||who called | |_____________
如果函数没有被调用为一个obeject的方法,就像你使用thisId
,JS就像它一样 – 它会回落到全局对象, this
将指向window
。
您可以使用functionName.call(context)
和functionName.apply(context,[arguments]);
以编程方式确定调用上下文functionName.apply(context,[arguments]);
,这是jQuery在幕后所做的事情:
$.fn.on(evt,callback)//simplified {//jQ sets up its own event handler that looks like this: //here, this point to $("#my_div") in your case, so: var jQhandler = function(e) { callback.apply(this,[e]);//passes the event as an argument }; this.addEventListener(evt,jQhandler,false);//<-- passes its handler by reference }
所以你可以做这个使用apply,在你的情况下 - 需要另一个anon。 要创建的函数对象,或者将函数直接传递给jQuery作为回调函数。 后者效率更高:需要更少的冗长和更少的function对象。
简而言之,这就是为什么@RoryMcCrossan是正确的,以及为什么有些人认为JS是世界上最容易被误解的语言:使用它的大部分人都不知道JS如何确定上下文。
正如旁注:ECMA5允许您使用.bind
方法将函数绑定到上下文,但这会让我们远离主题...