2014-12-02 67 views
0

我試圖端口下面的JavaScript代碼,以紅寶石: https://github.com/iguigova/snippets_js/blob/master/pokerIn4Hours/pokerIn4Hours.js無法理解的Javascript嵌套函數/關閉

認爲我已經大部分排序,這是給我的悲傷的功能是:

var kickers = function(idx){ // http://en.wikipedia.org/wiki/Kicker_(poker)   
    idx = idx || -15; 
    var notplayed = Math.max(input.length - 1/*player input*/ - 5, 0); 
    return function(all, cardinality, rank) { 
     return (all || 0) + (((cardinality == 1) && (notplayed-- <= 0)) ? rank * Math.pow(10, ++idx) : 0); 
    }; 
}(); 

,它被稱爲進一步下跌,像這樣:

k = kickers(k, cardsofrank[i], i); 

我是WO如果有人可以解釋這是如何在JavaScript中工作的話。內部函數有3個參數,外部只有1的事實令人困惑,尤其是考慮到它被3個參數調用。我想了解它正在努力完成什麼,以便我可以自信地移植代碼。

回答

0
var kickers = function(idx){ 
    var xyz;//below function in return statement can access this and argument idx 
    return function(...) {//this ensures that your kickers is infact a function 
    }; 
}();//invoke this function instantly due to() and assign the output to kickers 

當讀取Javascript解釋上述分配Kickers由於該函數本身返回一個函數,將執行匿名函數 ,該kickers現在將一功能(封閉)。 含義踢球功能必須將環境變量的引用(IDX和notplayed)

編輯:
1)凡有越來越IDX的價值 - 因爲沒有被傳遞,而調用函數(最後();)idx將被定義爲undefined,idx = idx || -15;將爲其賦值-15。

2)這可以重寫沒有內部功能? - 是的。但是目前的實現有一個優勢,其範圍idxnotplayed僅限於踢球功能,並且不能全局訪問。這裏是你如何可以直接把它寫成一個函數

/* now idx and notplayed is global- but its meant to be used only by kicker 
* we cant move it inside the function definition as it will behave as local variable to the function 
* and hence will be freed up once executed and you cannot maintain the state of idx and notplayed 
*/ 
var idx = -15; 
var notplayed = Math.max(input.length - 1/*player input*/ - 5, 0); 
var kickers = function(all, cardinality, rank) {    
    return(all || 0) + (((cardinality == 1) && (notplayed-- <= 0)) ? rank * Math.pow(10, ++idx) : 0); 
} 
+0

所以,我想我的後續問題將是: 1.凡越來越因爲函數「IDX」的值被稱爲馬上__without__一參數? 2.這可以重寫沒有內部功能?如果是這樣,這將是什麼樣子? – iank 2014-12-02 20:56:02

+0

@ user3871205我編輯了答案,以解決您的查詢 – Amitesh 2014-12-03 05:23:51

+1

好吧,所以'嵌套'的唯一原因是限制範圍。謝謝,我想我現在已經有了頭了! :) – iank 2014-12-03 21:06:05

1

function(idx)該函數返回一個新函數function(all, cardinality, rank),這個新函數依次由kickers變量引用。所以啓動器基本上指向你已經返回的內部函數。

打電話給你返回功能的唯一方法是這樣的kickers(k, cardsofrank[i], i)