开发者

Binding 'this' in the loop of an array

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜