Reputation: 779
While attempt to read "secrets of the javascript Ninja"(ok, so perhaps I am not qualify to read this book just yet) but I see below code and I understand what code is doing but part I really don't understand is where function(index) is being called. Is index arbitrary terms or some sort of javascript to indicate generic index?
<script type="text/javascript">
function forEach(list,callback) {
for (var n = 0; n < list.length; n++) {
callback.call(list[n],n);
}
}
var weapons = ['shuriken','katana','nunchucks'];
forEach(
weapons,
function(index){
function
 assert(this == weapons [index],
"Got the expected value of " + weapons [index]);
} );
</script>
Upvotes: 2
Views: 148
Reputation: 8632
index
it's an alias for the variable that will be available inside the execution context of the callback, hence available to the caller, the name could be whatever.
this is an example of a function used as a first class function (a crucial concept in javascript), that is pass them around as objects to define custom behaviour.
Upvotes: 1
Reputation: 943108
It is passed as the second argument to forEach
.
forEach(list,callback)
… to a variable called callback
.
So it is called here:
callback.call(list[n],n);
via the call method
Is index arbitrary terms or some sort of javascript to indicate generic index?
It's an argument name. You defined the name yourself. The value it gets passed is determined when you call the function.
Upvotes: 2