javascript - Binding 'this' in the loop of an array - Stack Overflow

I have a Javascript function with a namespace and I am using Prototype to execute a function. Example c

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 badges
Add a ment  | 

2 Answers 2

Reset to default 11

Use 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745192912a4615951.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信