2015-11-04 66 views
0

我遇到了这段代码,但是我在阅读时遇到了麻烦,我从来没有见过用这种方式编写的代码。Javascript函数写约定

showMenuButton[isOpened ? "hide" : "show"](); 
hideMenuButton[isOpened ? "show" : "hide"](); 
isOpened ? container.removeClass("hideMenu") : container.addClass("hideMenu"); 

是不是一样

if(isOpened="hide"){ 
showMenuButton(); 
} 
else{ 
hideMenuButton(); 
} 

有人能解释代码在做什么,他们为什么写这样?仅仅因为它们更短? (我从来没有在函数调用中看到[]]。

谢谢。

这里是完整的JavaScript代码。

menuToggle = $("#menuToggle"), 
     showMenuButton = $(".menuToggle_show"), 
     hideMenuButton = $(".menuToggle_hide"), 
     toggleSideMenu = function (isOpened) { 

     showMenuButton[isOpened ? "hide" : "show"](); 
     hideMenuButton[isOpened ? "show" : "hide"](); 

     isOpened ? container.removeClass("hideMenu") : container.addClass("hideMenu"); 
     } 

回答

1

JavaScript有2 ways of referring to objects/method calls - 的点表示法和方括号标记。他们互换,和等效,所以下面的2线将是相同的

var x = someObject.someProperty; 
// or 
var x = someObject["someProperty"]; 

这也适用于方法,如此反复follwoing两人双双工作(注意,从上面的差别是调用方法括号)

someObject.someFunction(); 
// or 
someObject["someFunction"](); 

现在,回顾一下你的问题,还有另一个窍门:三元运营商:

var result = someCondition ? trueResult : falseResult 

把所有这些组合起来

showMenuButton[isOpened ? "hide" : "show"](); 
hideMenuButton[isOpened ? "show" : "hide"](); 

相当于

if(isOpened){ 
    showMenuButton["hide"](); // or, showMenuButton.hide(); 
    hideMenuButton["show"](); // or, hideMenuButton.show(); 
} 
else{ 
    showMenuButton["show"](); // or, showMenuButton.show(); 
    hideMenuButton["hide"](); // or, hideMenuButton.hide(); 
} 

(它基本上切换取决于它是否是当前处于打开状态或不显示/隐藏按钮)

+0

你好,非常感谢你来清除该起来。他们是以这种方式写作的理由吗?似乎“if语句”更容易理解和调试。还是仅仅因为它更短?用这种方式编写代码是否有任何复杂性,可能不太可能弃用,但是其他方面呢?谢谢 – hcythp

0

那些是对象存储功能:

var functions={ 
    alertName:function(){ 
     alert('My name is Angel'); 
    }, 
    alertLastName:function(){ 
     alert('My last name is Cool'); 
    }, 
    alertMySite:function(){ 
     alert('angelcool.net'); 
    } 
} 

functions['alertMySite'](); 

http://jsfiddle.net/8ugav811/2/

0

是的,它正是这样调用函数hide()show(),从jQuery对象,三元运营商并使其更加紧凑,最友好的代码看,会是这样的:

if(isOpened ){ 
    showMenuButton.hide(); 
    hideMenuButton.show(); 
    container.removeClass("hideMenu"); 
}else{ 
    showMenuButton.show(); 
    hideMenuButton.hide(); 
    container.addClass("hideMenu"); 
}