Im a bit of a beginner when it comes to javascript constructs. Im trying in jquery, but not with much success. The following is a reduces version of my code:
var field1 = {
fieldId:"#field1",
field:"",
init:function(){
this.field = this;
$.ajax({
type:"GET",
url:'some/url/to/get/values/from',
cache:false,
success: function(data){
alert(field.fieldId);
}
});
}
};
field1.init();
Basically i want to be able to print out field.fieldid inside the success event but i end up with something most definetly not expected. I would hate having to write field1.field.fieldid everytime also since that would ruin when i figure out how to use extends and similar things.
Can anyone help me get “#field1” out when i do the alert(field.fieldId) ?
This is a classic case of You must remember
this. The simplest answer in your case is a local variable in your init function:Or alternately, use the
contextargument of theajaxfunction:Basically, in JavaScript, the value of
thisduring a function call is defined entirely by how a function is called, not where it’s defined as in some other languages (C++, Java, C#, …). When jQuery calls thesuccesscallback of theajaxfunction, it has to setthisto something. By default, it sets it to an object representing the settings of the ajax call, but usingcontextyou can tell jQuery to set it to something else, allowing you to usethiswithin the callback to mean the same thing asthiswhen you callajax.The first solution takes advantage of the fact that the
successcallback is a closure over the context of the call toinit(don’t worry, closures are not complicated), and so by creating a variable (self) and giving it the value ofthis, we can reliably refer to the object viaselfwithin the closure (thesuccesscallback).Ways in which
thisis set in JavaScript:When you call a function by getting the function reference from an object property as part of the same expression as the call,
thiswithin the function call will be the object from which you got the property. So given:then
Note that it has to be part of the same expression as the call. This does not work:
Using
callorapply. These are features of all JavaScript functions. They let you call the function and explicitly set whatthiswill be during the call. So given theobjabove:The only difference between
callandapplyis that when you usecall, if you want to pass arguments to the function, you include them as discrete arguments tocallas above (note we just passed"hi"as a second argument tocall, andcallpassed it on as the first argument to the function). Withapply, rather than an unlimited number of discrete arguments, the second argument is an array of arguments to pass to the function.