在MDC中,有大量代码片段意味着在不支持它们的浏览器中实现对新ECMAScript标准的支持,例如Array.prototype.map函数:
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;
};
}
Run Code Online (Sandbox Code Playgroud)
使用此功能的好处是什么(如果有的话)而不是
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;
}
Run Code Online (Sandbox Code Playgroud)
,var t = Object(this);而不是var t = this;和var len = t.length >>> 0;,而不是var len = t.length;?
小智 7
var len = t.length >>> 0;
Run Code Online (Sandbox Code Playgroud)
在这个问题中很好地涵盖了它.基本上它确保数字是非负32位int.
至于Object构造函数:
var t = Object(this);
Run Code Online (Sandbox Code Playgroud)
如果这是null或未定义,它将返回一个空对象.来自MDC Docs on Object
Object构造函数为给定值创建一个对象包装器.如果值为null或未定义,则它将创建并返回一个空对象,否则,它将返回与给定值对应的类型的对象.
它们只是快速纠正错误的方法.
编辑:我对thisp部分的思考太过分了.我假设使用arguments数组是一种确保参数默认为undefined的方法,但无论如何他们都是这样做的.Mike Hofer在评论中说得对.这是Mozilla的编码风格,用于指示可选参数.如果将null或undefined作为第一个参数传入,则Function.call默认为global.来自Function.call上的MDC Docs
thisArg:确定这个内部乐趣的价值.如果thisArg为null或未定义,则 这将是全局对象.否则,这将等于Object(thisArg)(如果thisArg已经是对象,则为thisArg,如果thisArg是相应类型的原始值,则为String,Boolean或Number).因此,当函数执行时,这个 =="对象"的类型总是正确的.
| 归档时间: |
|
| 查看次数: |
804 次 |
| 最近记录: |