[英]JavaScript double parenthesis in angularJs input directive's source code
在angularJs源代碼中,有我從未見過的語法。 有人可以在“(inputType [lowercase(attr.type)] || inputType.text)(scope,element,attr,ctrls [0],$ sniffer,$瀏覽器,$ filter,$ parse);“?
它的上下文:
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse);
}
}
}
};
}];
這只是一個常規函數調用,但是被調用的函數由第一部分確定:
(inputType[lowercase(attr.type)] || inputType.text)
在一個較小的示例中更容易理解:
var functionToCall = ...;
var obj = {
goodbye: function(name) { alert('Goodbye ' + name); }
hello: function(name) { alert('Hello ' + name); }
};
(obj[functionToCall] || obj.hello)(name);
如果functionToCall == 'goodbye'
,則調用obj.goodbye(name)
; 如果functionToCall == 'hello'
,則調用obj.hello(name)
。 但是,如果functionToCall
是其他任何東西,則默認為hello
。
也許您會像這樣更好地理解它:
var func = inputType[lowercase(attr.type)];
if(!func) func = inputType.text;
func(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse);
||
是邏輯OR運算符 。 expr1 || expr2
expr1 || expr2
返回expr1
,如果它可以被轉化為true; 否則,返回expr2
。
這可能意味着inputType[lowercase(attr.type)]
和inputType.text
是一個函數。 第二個括號包含參數。
考慮這種簡化的inputType
實現。
var inputType = {
text : function(scope, element, attr, ctrls, sniffer, browser, filter, parse){
//do stuff
},
button : function(scope, element, attr, ctrls, sniffer, browser, filter, parse){
//do stuff
}
}
當attr.type
返回文本或按鈕以外的其他內容時,默認為text函數並使用給定的參數調用它。
我不知道角度源在哪里,所以我不知道inputType
在哪里,但是它必須是一個對象,它具有許多用於不同輸入類型的函數,並且其“默認”值是text
。
這段代碼:
(inputType[lowercase(attr.type)] || inputType.text)
利用||
(邏輯或)運算符。 運算符采用兩個操作數,如果操作數為true
,則返回第一個(左)。 如果左操作數的計算結果為false
(或者重要的是undefined
),則它返回第二(右)操作數。
因此,這樣做是在inputType
對象中查找attr.type
。 如果在此找到它,則返回該函數; 如果不是,則返回分配給inputType.text
的函數。 下一組括號是傳遞給此結果函數的參數列表。
使用||
通過這種方式,可以非常方便地為傳入的參數設置默認值或后備值。 您可能已經看到的另一個速記解決方案是三元運算符:
var func = inputType[lowercase(attr.type)] ? inputType[lowercase(attr.type)] : inputType.text;
func( scope, element, attr, ... );
我認為||
版本在這里更加靈活,因為當您要檢查的值僅是true / false時,它將始終存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.