&&&的解释JavaScript的简写 [英] An explanation of && shorthand in JavaScript
问题描述
使用jQuery的水印插件,我试图jslint并最小化函数,但是我遇到了以前从未见过的语法,其中确实需要赋值或函数调用的表达式是>
Using a watermark plugin for jQuery, I'm attempting to jslint and minimize the functions but I've come across syntax I have never seen before wherein there are expressions where there really ought to be an assignment or function call:
(function($) {
$.fn.watermark = function(css, text) {
return this.each(function() {
var i = $(this), w;
i.focus(function() {
w && !(w=0) && i.removeClass(css).data('w',0).val('');
})
.blur(function() {
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
})
.closest('form').submit(function() {
w && i.val('');
});
i.blur();
});
};
$.fn.removeWatermark = function() {
return this.each(function() {
$(this).data('w') && $(this).val('');
});
};
})(jQuery);
我对以下几行特别感兴趣:
I'm specifically interested in the following lines:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
和
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
有人可以解释这个速记并重写这些功能,以便我可以比较它们以更好地自己理解速记吗?
Can someone explain this shorthand and rewrite these functions in such a way that I could compare them to better to understand the shorthand myself?
谢谢.
推荐答案
让我们打破您要询问的每个语句的各个组成部分:
Let's break each of the statements you're asking about down to their components:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
-
w
-w
是否为"true"? (在这种情况下检查!= 0
) -
!(w=0)
-将w
设置为0
,取相反的结果,以便&&
链继续进行 -
i.removeClass(css).data('w',0).val('')
-删除类,将数据设置为0
清除值. w
- Isw
"true"? (checking for!= 0
in this case)!(w=0)
- Setw
to0
, take the opposite of the result so the&&
chain continuesi.removeClass(css).data('w',0).val('')
- Remove the class, set the data to0
clear the value.
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
-
!i.val()
-输入是否为空? -
(w=1)
-将w
设置为1
-
i.addClass(css).data('w',1).val(text);
-添加类,将数据设置为1
,并将文本设置为任何水印文本. !i.val()
- Is the input empty?(w=1)
- Setw
to1
i.addClass(css).data('w',1).val(text);
- Add the class, set the data to1
and set the text to whatever the watermark text is.
这两个都是真正削减代码的语句,当然是以牺牲可读性为代价的.如果您正在查看缩小版本,这是很常见的;如果您不是 ,并且这是原始版本,请用色叉追逐作者,原始版本应比此IMO,尽管对于精简版来说也很好.
Both of these are just statements to really cut down on code, certainly at the expense of readability. If you're looking at a de-minified version this is very common, if you're not and this is the original, chase the author with a salad fork, the original should be more more readable than this IMO, though it's just fine for a minified version.
这篇关于&&&的解释JavaScript的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!