this keyword and closures

J

Jeff

I have a question about closures. Take for example the addBehavior
method below from the Low Pro library

Event.addBehavior = function(rules) {
var ab = this.addBehavior;
Object.extend(ab.rules, rules);

if (!ab.responderApplied) {
Ajax.Responders.register({
onComplete : function() {
if (Event.addBehavior.reassignAfterAjax)
setTimeout(function() { ab.reload() }, 10);
}
});
ab.responderApplied = true;
}

if (ab.autoTrigger) {
this.onReady(ab.load.bind(ab, rules));
}

};

var ab is initialized to this.addBehavior. It is then extended using
Object.extend(ab.rules.rules). However, in the Ajax.Responders
onComplete function, addBehavior is referenced using
Event.addBehavior.reassignAfterAjax instead of ab.reassignAfterAjax.
Then, immediately after, ab.reload is referenced. Why is this? Instead
of ab.rules, why wasn't
Object.extend(Event.addBehavior.rules, rules), or even
Object.extend(this.addBehavior.rules, rules)? Does it have to do with
closures?
 
J

Joost Diepenmaat

Jeff said:
I have a question about closures. Take for example the addBehavior
method below from the Low Pro library

Never heard of that library, but ok.
Event.addBehavior = function(rules) {
var ab = this.addBehavior;
Object.extend(ab.rules, rules);

if (!ab.responderApplied) {
Ajax.Responders.register({
onComplete : function() {
if (Event.addBehavior.reassignAfterAjax)
setTimeout(function() { ab.reload() }, 10);
}
});
ab.responderApplied = true;
}

if (ab.autoTrigger) {
this.onReady(ab.load.bind(ab, rules));
}

};

var ab is initialized to this.addBehavior. It is then extended using
Object.extend(ab.rules.rules).
yes.

However, in the Ajax.Responders onComplete function, addBehavior is
referenced using Event.addBehavior.reassignAfterAjax instead of
ab.reassignAfterAjax.

It's not clear from the code that Event.addBehaviour.reassignAfterAjax
=== ab.reassignAfterAjax, though it probably is.
Then, immediately after, ab.reload is referenced. Why is this? Instead
of ab.rules, why wasn't
Object.extend(Event.addBehavior.rules, rules), or even

because it's shorter?
Object.extend(this.addBehavior.rules, rules)? Does it have to do with
closures?

since you can't close over this, yes, it has to do with closures. this
is NOT a variable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top