速记 javascript 语法是否适用于较旧的浏览器?

coc*_*cco -3 javascript

今天我在玩速记语法..发现了两种新的很酷的方法来编写冗长乏味的if语法,还学到了关于闭包的新东西......

这是我想出来的。

这是一个带有一个 eventHandler 的手风琴菜单的切换功能。

function h(e){
 var p='parentNode',a=e.target,b=a[p],f=48,u='px',y=b[p];
 !y.c||(y.c==b||(y.c.style.height=f+u,y.c.x=f)),
 y.c=y.c==b?null:b,
 a!=b.firstChild||(b.x=b.x>f?f:
 (f+b.childNodes[1].offsetHeight),b.style.height=b.x+u)
}
Run Code Online (Sandbox Code Playgroud)

这是示例。

http://jsfiddle.net/YjCbM/(使用 Chrome 29 测试)

有一个错误..这是工作http://jsfiddle.net/YjCbM/1/

在这个例子中,我使用 e.target、webkit css3 和其他各种 ie 和其他浏览器不支持的东西,但除此之外……这个速记语法在旧版/其他浏览器上是否有效?

ps.: 不要在 jsfiddle 中整理代码,否则无效


在我得到一些答案后编辑..

一些有用的速记

var W=window,D=W.document,G='getElementById',
E=W.addEventListener?'addEventListener':'attachEvent',
// this awesome as i don't use jQuery. 
// this way i have a short getElementbyId() like jQuery's $()
// and also a ie compatible addEventListener.

a=D[G](x);
//document.getElementById(x)
a[E]('click',handler);
//a.addEventListener() or a.attachEvent()

a=x?y:x
//if x is defined, true, or not 0 it will take the y value 
if ( x == true ) {
 a = y;
}else{
 a = x;
}

a=x||y;
//if x is not defined it will take y
if ( x == true ) {
 a = x
}else{
 a = y
}


x||(x=y,alert(x)) // <- this is fabulous
// if x is  not defined, not true, or 0 it will set the x with the y value 
// and alert x
if ( x == 'undefined' ) {
 x = y;
 alert ( x );
}
// how manytimes did it happen that you wanted to do just a short check but you hat to 
//set 2-3 variables and could not use a simple  a=x||y
// whith this shorthand you can.

var a = 1;
var b;
var c = a;
// is the same as
var a=1,b,c=a;
Run Code Online (Sandbox Code Playgroud)

编辑2

  1. 我真的不知道这种类型的闭包和速记
  2. 重点不是一直以这种方式编写 javascript,而是要保留一个漂亮的代码,然后以这种方式手动重写它以获得更快和更短的代码
  3. 正如您在评论中所读到的那样“嘿,看看我能做什么!” ......再次......在我发布这个函数之前我不知道这一点,当时我只在chrome中进行了测试。是的,我多年来一直在写javascript......但不是这种速记和按位运算符。这是对我来说是新的东西。
  4. 在测试了一些压缩实用程序 yuy obfuscator 等之后,我发现它们无法像这样压缩您的代码,因此无论如何您都必须编写好的代码,并且不希望各种压缩器为您做到这一点,所以您想尝试手动缩小您的代码?...是的,这就是我想要做的。

我收到了所有这些downvotes的问题禁令。但我真的不明白为什么我得到了这么多的反对...请解释你的反对

Doo*_*nob 5

如果您指的是三元运算符 ,?:那么是的,所有浏览器都支持它。

它是这样使用的:

condition ? ifTrue : ifFalse
Run Code Online (Sandbox Code Playgroud)

例如:

'You have ' + (milkAmount <= 0 ? 'no' : (milkAmount + ' cups')) + ' of milk!'
Run Code Online (Sandbox Code Playgroud)

如果您指的是 or 运算符||,那么也可以。例如:

a || b || c
Run Code Online (Sandbox Code Playgroud)

这将找到的第一个变量出来abc选择的第一个不是falsyundefined0falseNaN,等)。

  • @cocco 请使用谷歌,不要在评论中提出后续问题。快速五秒钟的谷歌搜索会给你答案。 (3认同)