0

I have the following jquery:

function GetSelectedCheckboxIds(className) {
    var ln = className.length;
    return $('.' + 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?

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, you're right. It was my argument (classname) that was wrong.
@boris: Happens to us all. :-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.