在MDC有大量的代碼片段是爲了執行在瀏覽器中新的ECMAScript標準不支持他們,如Array.prototype.map
功能支持:爲什麼用這種方式編寫MDC原型函數?
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
res[i] = fun.call(thisp, t[i], i, t);
}
return res;
};
}
有什麼好處(如果有任何)的使用此功能,而不是
function(fun, thisp)
{
// same code, just without the "var thisp = arguments[1];" line:
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = new Array(len);
for (var i = 0; i < len; i++)
{
if (i in t)
res[i] = fun.call(thisp, t[i], i, t);
}
return res;
}
,var t = Object(this);
而不是var t = this;
和var len = t.length >>> 0;
而非var len = t.length;
?
謝謝! (但是,你知道那個'function(fun,thisp)'staff嗎?) – 2011-05-11 19:22:30
是的,我剛剛意識到我錯過了,暫時編輯。 – 2011-05-11 19:24:13
'fun(fun/*,thisp * /)'是一個編碼風格*,表示thisp是一個可選參數。當然,'fun'是一個委託函數,後來使用'fun.call'調用,將'thisp'作爲「context」傳遞(即當函數執行時它將成爲'this'的值)。 – 2011-05-11 19:36:19