1
function jQueryValidatorWrapper(formId, rules, messages) {
    var validator = $("form:visible[id='" + formId + "']").validate({
                         onchange: false,
                         messages: messages,
                         rules: rules
                     });

    this.validate = function (hideErrors) {
        var showErrorMessage = hideErrors ? false : true;

        // What does 'validator' refer to?
        var result = validator.form();
    };
}

When I execute this,

var validatorObj = new jQueryValidatorWrapper('testForm', [], []);
validatorObj.validate();

The jQueryValidatorWrapper function had only one method declared with this, so when the constructor executed, it simply created an object with the validate method.

What happens to validator variable declared inside jQueryValidatorWrapper? It is not prefixed with this so it is not part of the object being constructed.

Is the validator variable a global? or is it part of the closure which is the validate method?

2
  • 1
    validator is not a global variable... it will exists in the closure though Commented Oct 14, 2014 at 5:17
  • 2
    A constructor function is still a function. There is no difference between how local variables are handled or scope works. Commented Oct 14, 2014 at 5:19

1 Answer 1

4

The local validator variable is not global; it's merely accessible in the validate method because of the closure.

It can be considered a "private member" of the jQueryValidatorWrapper object, per Douglas Crockford's article here: http://javascript.crockford.com/private.html

Same goes for the 3 constructor parameters.

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

3 Comments

So, if I were to create multiple instances of jQueryValidatorWrapper with different data for the 3 constructor parameters each time, would the closure environment be modified for the previous instances?
Nope, they each get their own copy. Here's a fiddle to illustrate that: jsfiddle.net/sck02myt
@Lakeland-FL—each time a function is called, an entirely new execution context is created so an entirely new closure is also created in this instance.

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.