I’ve built a working page with lots of javascript. The javascript is placed in between the <head></head> tags without a problem, but I really want to move it an external file.
I though I would be able to simply cut and paste all the code minus <script></script> tags but incuding $(document).ready(function() { }); it into a .js file and reference it in the usual way, but it’s causing me big headaches. Can anyone suggest why I can’t just do this?
As a compromise, I though I would detach at least some of my functions and put them in an external file but there are problems there too.
function look(){
var word_id = $(this).attr("id");
// Other stuff
var value = $(this).val();
// Other stuff
}
$("input").focus(function(){look();});
In the above function, this is not the this it used to be when the code looked like this:
$("input").focus(function(){
var word_id = $(this).attr("id");
// Other stuff
var value = $(this).val();
// Other stuff
});
I hope that a really clever person will spot my errors easily. Many thanks, Patrick.
When you call a function with no context specified, as you are calling
look(), thethiskeyword inside that function will be the global object.In your case you could only pass a reference to your function, and it will work properly:
Also, it might be helpful to know that the
thiskeyword is not completely implicit, can be set explicitly by using thecallandapplyfunctions:And that the context (the
thiskeyword) is set implicitly in the following cases:1- When calling a function that is member of an object, eg.:
2- When calling a function with the
newoperator:3- When calling a function not associated with any object: