2014-12-02 63 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)