I have a Javascript function with a namespace and I am using Prototype to execute a function. Example code:
GUI.Title = {
initialise: function() {
var elements = $$('a');
this.show(); /* now it refers to the namespace */
elements.each(function(element) {
this.show(); /* this refers to the window object, not to the namespace */
});
},
show: function() {
element.show();
}
}
'this' refers to the namespace outside the each-function and inside the each it refers to the window.
Can someone explain to me how I can use 'this' in the each-loop as a referer to the namespace?
I am using Prototype.
I have a Javascript function with a namespace and I am using Prototype to execute a function. Example code:
GUI.Title = {
initialise: function() {
var elements = $$('a');
this.show(); /* now it refers to the namespace */
elements.each(function(element) {
this.show(); /* this refers to the window object, not to the namespace */
});
},
show: function() {
element.show();
}
}
'this' refers to the namespace outside the each-function and inside the each it refers to the window.
Can someone explain to me how I can use 'this' in the each-loop as a referer to the namespace?
I am using Prototype.
Share Improve this question edited Dec 28, 2011 at 10:58 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Feb 21, 2011 at 16:37 SanderSander 1,2741 gold badge13 silver badges26 bronze badges2 Answers
Reset to default 11Use Prototype's bind
method to modify what this
means inside the function.
elements.each(function(element) {
this.show();
}.bind(this));
replace
this.show(); /* now it refers to the namespace */
elements.each(function(element) {
this.show(); /* this refers to the window object, not to the namespace */
});
with
var scope = this;
elements.each(function(element) {
scope.show(); /* this refers to the window object, not to the namespace */
});
what you are doing is creating a closure, the 'scope' var gets 'closed-in' to your each function lexically. Note that this approach is not prototype specific, it's a general javascript technique.