[英]How does anonymous functions work in jQuery/Javascript?
How does anonymous function know what parameters are being passed in? 匿名函数如何知道传入的参数? For example,
例如,
Case 1: 情况1:
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
Case 2: 案例2:
$( "li" ).each(function(e) {
e.preventDefault();
});
Case 3: 案例3:
$( "li" ).each(function( index, element ) {
console.log( index + ": " + element + $( this ).text() );
});
In each of these cases, how does the anonymous function know what e
, index
, element
are? 在每种情况下,匿名函数如何知道
e
, index
, element
是什么?
Because the code in each
will call the function you pass it with the arguments. 因为
each
代码中的代码都会调用函数,并使用参数传递它。
function notEach(callback) {
callback(1,2,3);
}
notEach(function (one, two, three) {
console.log(one, two three);
});
If we can speak of each
as if it's a little robot, each
tells the function what its arguments are. 如果我们可以说
each
都是一个小机器人, each
告诉函数它的参数是什么。 It picks up the collection and the function, puts the elements of the collection into the function one at a time, and sticks the outputs together as a collection. 它拾取集合和函数,将集合的元素一次放入函数中,并将输出作为集合粘在一起。 http://api.jquery.com/jquery.each/
http://api.jquery.com/jquery.each/
You should understand that when you write an anonymous function, it's both a procedure and an object. 你应该明白,当你编写一个匿名函数时,它既是一个过程,也是一个对象。 You are simultaneously defining for Javascript how to carry out that function ("knowing how" to call it) and what that function is ("knowing that" it is a particular object).
您同时为Javascript定义如何执行该功能(“知道如何”调用它)以及该功能是什么(“知道”它是一个特定的对象)。 Some languages are still in use where a function is not an object.
某些语言仍在使用,其中函数不是对象。 So maybe that fact was confusing when you encountered it here.
所以,当你在这里遇到它时,这个事实可能令人困惑。
naive implementation of each
function: each
功能的天真实现 :
function $(selector) {
var elements = document.querySelectorAll(selector);
return {
each: function (fn) {
for (var i = 0; i < elements.length; i++) {
fn(i, elements[i]);
}
}
};
}
The jQuery function returns an object with an each
function. jQuery函数返回一个包含
each
函数的对象。 This function has access to the matched elements and iterates over them. 此函数可以访问匹配的元素并对它们进行迭代。 It can call the function you gave it on every iteration and pass the current index and corresponding element to it.
它可以在每次迭代时调用您给它的函数,并将当前索引和相应的元素传递给它。
Your second case doesn't make much sense to me. 你的第二个案例对我来说没什么意义。 As far as I know jQuery , no event is passed to the
each
function. 据我所知jQuery ,没有事件传递给
each
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.