javascript - 功能的冗余类型检查?

标签 javascript typechecking

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/

相关文章:

javascript : filter array of objects using another array as filter

javascript - 使用 html 或 javascript 重定向

php - 如何从电子邮件链接或网页打开 Outlook 日历?

c - 如何在 C 中使用静态断言来检查传递给宏的参数类型

Python 3.6 类型检查 : numpy arrays and use defined classes

javascript - 什么在函数中创建函数?

javascript - 如何在 Javascript 中创建街机样式名称输入?

list - 在 ANTLR 中返回列表以进行类型检查,语言 java

c++ - 如何检查函数的模板参数是否具有某种类型?

python - 为什么变量的类型提示不作为函数参数的类型提示处理?