Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  163] [ 2]  / answers: 1 / hits: 24855  / 15 Years ago, thu, october 8, 2009, 12:00:00

I'm trying to understand why in javascript, you might want to change the context of a function. I'm looking for a real world example or something which will help me understand how / why this technique is used and what its significance is.



The technique is illustrated using this example (from http://ejohn.org/apps/learn/#25)



var object = {}; 
function fn(){
return this;
}
assert( fn() == this, The context is the global object. );
assert( fn.call(object) == object, The context is changed to a specific object. );

More From » function

 Answers
113

jQuery makes use of it to good effect:



$('a').each(function() {
// this is an a element - very useful
});


The actual jQuery code looks like this:



for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}


If it just did callback( name, object[ name ] ) then this wouldn't be set to the current object in your iterator and you'd have to use the parameter instead. Basically it just makes things easier.


[#98553] Friday, October 2, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
berenices

Total Points: 104
Total Questions: 106
Total Answers: 106

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
berenices questions
;