开发者

JavaScript variable isn't known to inline function (scoping?)

I have the following jquery:

function GetSelectedCheckboxIds(className) {
    var ln = className.length;
    ret开发者_运维知识库urn $('.' + className + ':checked').map(function() {
        return this.id.substring(ln);
    }).get();
}

The variable ln is unknown inside the scope of the map function.

What are the scoping rules here and how can I pass my ln value to the inner function?


The variable ln is not unknown within the scoping function (working live here), what makes you think that it is? Because the function closes over the execution context of the call to GetSelectedCheckboxIds, ln will be accessible to it.

The scoping rules are fairly simple, but they're unlike many other languages. More in this article about closures, but basically, a function "closes over" (has reference to) all data in scope in the execution context in which it was created. In your case, the anonymous function was created inside the execution context of a call to GetSelectedCheckboxIds and so has access to the arguments and variables defined in that context (className and ln, in this case), as well as any inherited from enclosing contexts (including the global execution context, which is how JavaScript does global variables).


Your code works fine for me: http://jsfiddle.net/ThiefMaster/k3hzQ/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜