Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 装订';这';在数组的循环中_Javascript_Prototypejs_This - Fatal编程技术网

Javascript 装订';这';在数组的循环中

Javascript 装订';这';在数组的循环中,javascript,prototypejs,this,Javascript,Prototypejs,This,我有一个带有名称空间的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 windo

我有一个带有名称空间的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();
 }
}
“this”指的是each函数外部和each函数内部的名称空间,它指的是窗口

有人能告诉我如何在每个循环中使用“this”作为名称空间的引用吗

我正在使用原型。

替换

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

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


您所做的是创建一个闭包,“scope”变量在词汇上“closed in”到您的每个函数。请注意,这种方法不是特定于原型的,它是一种通用的javascript技术。

使用原型的
bind
方法来修改函数内部的
含义

elements.each(function(element) {
   this.show();
}.bind(this));

这会奏效的。由于原型是可用的,
bind
稍微整洁一点。给了你一个向上投票的机会,因为它对任何不使用原型的读者都很有用。+1,因为你的答案是特定于原型的。-我编辑了我的答案,以表明我的答案更像是一种通用的javascript方法。请注意,在未来(我希望不会太远),这将是一种有效的“javascript方法”,
bind
现在是ECMAScript第五版规范的一部分:)非常感谢,我知道了“bind”,但是我不知道解决这个问题的语法!现在我知道了,谢谢:)有时候原型手册有点难理解。。。
elements.each(function(element) {
   this.show();
}.bind(this));