This is kind of funky. But take a look at the code snippet below :
$('.classname').bind('click', somefunction);
function somefunction() {
console.log($(this)); // **displays[<div>,context<div>]**
}
And if I tweak the above to:
$('.classname').bind('click', function(){ somefunction(); });
function somefunction(){
console.log($(this)); // **displays [Window]**
}
I am not quite sure why ‘this’ assumes two different values depending on how the function is being called back. The thing is, I do need this to be ,context and the function to be called like
function(event){ somefunction(event); }
because I need the event. But not quite sure what’s up here.
Any leads, people?
That’s exactly how
thisworks in JavaScript. Its value is based on how the function was called.You can manually set it to the value you want using
.callor.apply.Now there’s no need to modify
somefunction. By invoking it with.call(), you’re manually setting thethisvalue to whatever you pass as the first argument.