最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论