好的,我的问题来 self 试图理解的一本书中的一个例子。请记住,我刚刚接触 javascript。
因此我们设置了对象并定义了函数 foreach。它采用另一个函数作为参数,并为属于集合的数组“值”的每个项目调用它。
set.foreach = function(f,c) {
for(var i = 0; i < this.values.length; i++)
f.call(c,this.values[i]);
};
到目前为止一切顺利..
但是我无法理解第二个片段中 foreach 函数的用法。特别是我不理解变量 v 的作用。它在书中其他地方没有定义,我真的很难过了解这是如何工作的。我们在 set 中定义另一个函数,将值作为数组
set.toArray = function() {
var a = [];
this.foreach(function(v) { a.push(v); }); //where did v came from???
return a;
}
最佳答案
set.foreach = function(f,c) {
for(var i = 0; i < this.values.length; i++)
f.call(c,this.values[i]);
}; // ^-------------- being passed right here
您传入的函数是f
,调用f
时将其调用上下文的this
值设置为c
和 this.values[i]
作为第一个参数传递。
// ------v---------your function "f" in the forEach
this.foreach(function(v) { a.push(v); });
// ------------^------references the first argument (after the "this" arg)
// that was passed to "f"
这是一个更简单的例子:
这个函数接受一个函数作为参数。它唯一做的就是调用函数:
function my_func( fn ) {
fn();
}
// call my_func, which will call the function you give it
my_func( function() { alert( "hi" ); } );
实例: http://jsfiddle.net/6a54b/1/
...因此将函数传递给 my_func
将提示字符串“hi”。不足为奇。
但是如果 my_func
提供了要提醒的值呢?
function my_func( fn ) {
fn( "message from my_func" ); // call the fn passed, giving it an argument
} // ^------------------------------------------------|
// |
// v------references the arg passed by my_func---|
my_func( function( arg ) { alert( arg ); } );
实例: http://jsfiddle.net/6a54b/
现在您可以看到一个参数被传递给我们发送过来的函数,我们使用 arg
参数引用该参数。
它会提醒 my_func
给它的任何东西。
我们甚至可以更进一步,通过将第二个参数传递给 my_func
,my_func
将简单地将其传递给我们传入的函数。
function my_func( fn, str ) {
fn( str ); // call the fn passed, giving it
} // the string we passed in
// v------the arg we passed here-----v
my_func( function( arg ) { alert( arg ); }, "I'm getting dizzy!" );
实例: http://jsfiddle.net/6a54b/2/
而且你可以看到,这两个参数都被赋予了 my_func
,my_func
调用了我们传入的函数,将我们给它的字符串参数传递给它。
关于javascript - javascript中的foreach函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6434816/