[英]Is var db = window.openDatabase && openDatabase(); a good way to avoid errors?
Is this a good way to avoid errors? 这是避免错误的好方法吗?
var sql_db = window.openDatabase && openDatabase('table', '1.0', 'description', 4096);
It seems to work, but is this a good way to avoid errors if a feature isn't implemented? 似乎可行,但是如果未实现功能,这是否是避免错误的好方法? Later on I'll just check if
sql_db
is undefined
/ null
/ false
. 稍后,我将仅检查
sql_db
是否undefined
/ null
/ false
。
Does it work in all browsers, and does it return undefined
, null
or false
if window.openDatabase
isn't supported? 它可以在所有浏览器中使用吗?如果不支持
window.openDatabase
,它会返回undefined
, null
或false
吗?
Please note that this isn't only about openDatabase
but rather any feature that may not be implemented in all browsers. 请注意,这不仅涉及
openDatabase
,还涉及并非所有浏览器都可能实现的任何功能。 I'm already doing window.console && console.log()
and that works fine, but in that case I'm not saving any object to a variable. 我已经在执行
window.console && console.log()
,但工作正常,但是在那种情况下,我没有将任何对象保存到变量中。
Yes, that's fine, although I'd suggest adding the window.
是的,那很好,尽管我建议添加该
window.
part after the &&
as well, just to prevent conflict with any local variables. 以及
&&
之后的部分,只是为了防止与任何局部变量冲突。
If the global variable is not defined, it will return undefined
- this behaviour is consistent across browsers, however keep in mind that undefined
is not a reserved word and can theoretically be overwritten. 如果
undefined
全局变量,则它将返回undefined
-此行为在浏览器中是一致的,但是请记住, undefined
不是保留字,并且在理论上可以被覆盖。 Why someone would do that is beyond me, but it's good to know. 为什么有人会这样做,这超出了我,但很高兴知道。
I'm not entirely convinced whether this is a good idea for this specific case. 对于这个特定案例,我并不完全相信这是否是一个好主意。
For console && console.log
, I think it's pretty good, but if you're using it with the openDatabase
call then maybe not. 对于
console && console.log
,我认为它相当不错,但是如果将它与openDatabase
调用一起使用,则可能不会。
Why? 为什么?
If you have a variable that you use for database calls, sql_db
, what if it's null? 如果您有一个用于数据库调用的变量
sql_db
,如果它为null怎么办? It's going to cause an error. 这将导致错误。 Are you going to prefix every single use with
sql_db &&
? 您是否要在每次使用时加
sql_db &&
前缀? It feels like a kludge and it might not even be possible to always do that. 感觉就像是在跳动,甚至不可能总是这样做。
In a case where you actually will be using the result of the call for something, you probably should just opt for a normal if-else check. 在实际上您将使用调用结果的情况下,您可能应该只选择常规的if-else检查。 This way you can detect the failure early, and the code which depends on the result of that will work more reliably without requiring boilerplate variable checks.
这样,您就可以及早发现故障,而依赖于结果的代码将更可靠地工作,而无需进行样板变量检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.