views:

39

answers:

2

JavaScript in modern browsers includes the Array.forEach method that lets you write this:

[1,2,3].foreach(function(num){ alert(num); }); // alerts 1, then 2, then 3

For browsers that don't have Array.forEach on the Array prototype, MDC provides an implementation that does the same thing:

if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

Why does this implementation use /* and */ in the function definition? I.e. why is it written function(fun /*, thisp*/) instead of function(fun, thisp)?

+2  A: 

Because it's a comment.

function(fun /*, thisp*/) is the same as function(fun). There is no second argument in the function header.

In the middle of the function you see the variable thisp being declared, and assigned the value of the second argument. The comment in the function definition is just there to point out that you can call the function with two arguments, although the two arguments are not defined in the function header.

Guffa
My only question is why do they do it this way. Simply uncommenting `thisp` in the function header would have the exact same effect as `var thisp = arguments[1];` and it would save a line of code. What am I missing?
MooGoo
@MooGoo: Yes, the usage doesn't seem motivated in this case. It can be used to suggest that an argument is optional, but there is no code here to handle that; if you don't supply the argument, the value will be undefined. Perhaps that is the intended behaviour, but there is nothing in the code that suggests that.
Guffa
A: 

Well you are taking it too much cautiously and syntactically. Its just a comment.

When they say,

function(fun /*, thisp*/) {
   // body
}

they are actually indicating an option, that you can uncomment it, and send thisp as an argument, instead of declaring it in function body.

simplyharsh