JavaScript 编码技术还是糟糕的代码?
在调试别人编写的 JavaScript 时,我遇到了一些我以前从未见过的代码。这是一个示例:
function doSomething() {
//doing something here...
}
function doItNow() {
//other logic...
doSomething && doSomething(); // <=== What's this?
}
函数 doItNow() 中第二行的目的是检查 doSomething 是否存在然后调用它?就像这样:
function doItNow() {
//other logic...
if (doSomething) {
doSomething();
}
}
JSLint 不喜欢它,我不想在我的应用程序中出现错误的代码。有什么见解吗?
While debugging javascript written by someone else, I came across some code that I've not seen before. Here's a sample:
function doSomething() {
//doing something here...
}
function doItNow() {
//other logic...
doSomething && doSomething(); // <=== What's this?
}
Is the purpose of the 2nd line in function doItNow() to check if doSomething exists and then call it? Like so:
function doItNow() {
//other logic...
if (doSomething) {
doSomething();
}
}
JSLint does not like it and I'd rather not have bad code in my app. Any insights?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这确实是一个“简写”。仅当左侧作为
if()
语句传递时,右侧才会执行。Google Closure Compiler 和其他压缩器利用了这一点;如果您的输入是
if(a) a()
,它将产生a&&a()
您可以对
||
执行相同的操作code>,例如:可以写成
It's a 'shorthand' indeed. The right side is only executed when the left side passes as
if()
statement.Google Closure Compiler and other minifiers take advantage of this; if your input is
if(a) a()
, it will result ina&&a()
You could do the same with
||
, for example:can be written as
是的,您的两个示例是“等效的”,
&&
运算符执行 短路评估。如果第一个操作数表达式产生 falsey 值(例如
null
、undefined
、0
、NaN
,一个空字符串,当然还有false
),第二个操作数表达式将不会被求值,如果值为真 >,将进行函数调用。但如果
doSomething
尚未声明,您的两个示例都会失败。如果代码中引用了未声明的标识符,您将收到
ReferenceError
异常,例如:如果您想要:
您可以:
typeof
运算符 可以安全地用于不存在的标识符,此外,通过检查 doSomething 是否是一个函数,您可以确保能够调用它。Yes, your two examples are "equivalent", the
&&
operator performs short-circuit evaluation.If the first operand expression yields a falsey value (such as
null
,undefined
,0
,NaN
, an empty string, and of coursefalse
), the second operand expression will not be evaluated, and if the value is truthy, the function call will be made.But if
doSomething
hasn't been declared, your both examples will fail.If an identifier that's not declared, is referenced on code, you will get a
ReferenceError
exception, e.g.:If you want to:
You can:
The
typeof
operator can be safely used on identifiers that don't exist, additionally, by checking thatdoSomething
is a function, you make sure that you will be able to invoke it.在比较中调用函数(或赋值等)通常是一个坏主意。人们通常不认为比较会产生副作用。这种情况很简单,可能是合理的,但如果有人不理解约定,他们可能不得不在 StackOverflow 上询问;)
Calling functions (or assignments, etc) in comparisons is generally a bad idea. People don't usually expect comparisons to have side effects. This case is simple enough that it might be justifiable, but if someone doesn't understand the convention they might have to ask on StackOverflow ;)