I’m trying to improve my JS skills and I’ve rewritten a bunch of code as a namespaced object literal (I think.) But now I have a “this”-related problem. Help me understand?
Here is abbreviated code.
var MYAPP = {
init: function(){
$(document).on("click",".showLove", MYAPP.showLove);
},
showLove: function(){
var thisId = MYAPP.findId();
$.post(//// do AJAXy stuff using thisId);
},
findId: function(){
var thisClass = $(this).attr('class');
var thisIdPos = thisClass.indexOf("id-")+3;
var thisId = thisClass.substr(thisIdPos, 3);
return thisId;
}
}
So I’m sure you probably see the problem. In the findId function $this is undefined and I get an error. Earlier I had the findId logic in showLove and everything worked. I moved the findId logic to it’s own method because it was being used in a few different places.
So let me just ask this -> Why does $(this) point to the correct element in ‘showLove’ .. but not in ‘findId’? Since ‘findId’ is called from inside ‘showLove’, shouldn’t it have access to the same variables, including $(this)? Is this my first “self = this” situation?
I know this is a basic question, but if someone could help me understand, I’d .. uh.. ‘showLove’.
You’re passing
MYAPP.showLoveto jQuery and saying “attach this function as a click handler to the document”.When you do this,
MYAPP.showLoveforgets it was attached toMYAPP, as you’re only passing the function, with no reference to the namespace.Therefore, when
showLovegets executed as a click handler,thisis no longerMYAPP. Normally when you detach a function from an objectthisbecomes eitherwindoworundefined(ES5). However, jQuery decidesthisshould be the.showLoveelement that was clicked, by usingcall()orapply().When you call
MYAPP.findId()inshowLovehowever,thisis still set toMYAPP; as that’s whatfindIdis attached to (you’re calling the method onMYAPP).To fix this (no pun intended), you can either pass the value of
thistofindId(preferred, IMO), or usecall()/apply().or: