在数组的循环中绑定'this'

San*_*der 2 javascript this prototypejs

我有一个带命名空间的Javascript函数,我使用Prototype来执行一个函数.示例代码:

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();
 }
}
Run Code Online (Sandbox Code Playgroud)

'this'指的是每个函数外部的命名空间,每个函数内部都指向窗口.

有人可以向我解释我如何在每个循环中使用'this'作为名称空间的引用者?

我正在使用Prototype.

Nic*_*ick 11

使用Prototype的bind方法修改this函数内部的含义.

elements.each(function(element) {
   this.show();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

  • +1,因为你的答案是原型特定的. - 我编辑了我的答案,表明我的答案更像是一般的javascript方式. (2认同)
  • 请注意,在将来(不是太远,我希望),这将是一个有效的"javascript方式","bind"现在是ECMAScript第5版规范的一部分.:) (2认同)

hvg*_*des 7

更换

this.show(); /* now it refers to the namespace */

elements.each(function(element) {
   this.show(); /* this refers to the window object, not to the namespace */
});
Run Code Online (Sandbox Code Playgroud)

var scope = this;
elements.each(function(element) {
   scope.show(); /* this refers to the window object, not to the namespace */
});
Run Code Online (Sandbox Code Playgroud)

你正在做的是创建一个闭包,'scope'var以词法方式"封闭"到你的每个函数.请注意,此方法不是原型特定的,它是一种通用的JavaScript技术.

  • 这会奏效.由于Prototype可用,`bind`有点整洁.给你一个upvote,因为它对任何阅读不使用Prototype的人都有用. (4认同)