开发者

What do the comment characters in MDC's forEach do?

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)?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜