在 Array.prototype.forEach
js mdn 的 Polyfill 部分,您可以找到以下检查:
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
在这种特定情况下,为什么还要检查功能?在我的测试中,直接调用该函数会产生完全相同的行为
var callback;
callback();
// Uncaught TypeError: callback is not a function
var callback = "";
callback();
// Uncaught TypeError: callback is not a function
var callback = 2;
callback();
// Uncaught TypeError: callback is not a function
var callback = [];
callback();
// Uncaught TypeError: callback is not a function
var callback = {};
callback();
// Uncaught TypeError: callback is not a function
实际上这种字符串连接有点糟糕,因为我们可能会看到 [object Object] is not a function"
:
function newCallback(val){
if (typeof val !== 'function') {
throw new TypeError(val+ ' is not a function');
}
}
newCallback({});
//Uncaught TypeError: [object Object] is not a function
最佳答案
In this specific case, why bother checking for function?
如果数组为空,则不会尝试调用该函数,但它 should still fail .
[].forEach('foo')
当元素访问有副作用时,非空数组也有区别:
let foo = {
get [0]() {
alert(1);
}
};
Array.prototype.forEach.call(foo, …);
// alert shows up if the early type check is missing
关于javascript - 功能的冗余类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49643407/