[英]How do you check for null or undefined on a variable assigned to a missing anonymous function expression?
在注释掉下面的匿名函数表达式“a”时,如何正确检查“b”上的 NULL? 用例:假设“a”是分配给“b”的页内 JS 包含(库),但库无法加载,现在我们有一个控制台错误。
var a = function () { return 'Success!'; } // Exclude this line
var b = a();
if (typeof b !== 'undefined' || b !== null) { // These checks do not work.
console.log(b);
} else {
console.log('Failed!');
}
如果我正确理解您的用例,这行代码就在您的应用程序中:
var b = a();
如果这是正确的,您可以有条件地重新分配a
本身或使用新函数或对象。
当您要检查全局变量是否存在时,这是一种常见模式。
这是当a
不存在时的运行示例:
// library //var a = function () { return 'Success!'; } // Exclude this line // my app var a = a || function(){}; var b = a(); if (b) { console.log(b); } else { console.log('Failed!'); }
当a
存在时,这里是相同的代码:
// library var a = function () { return 'Success!'; } // Exclude this line // my app var a = a || function(){}; var b = a(); if (b) { console.log(b); } else { console.log('Failed!'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.