Developer
Developer

Reputation: 18709

How are variables declared in constructor functions in JavaScript treated?

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?

Upvotes: 1

Views: 113

Answers (1)

Troy Gizzi
Troy Gizzi

Reputation: 2519

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.

Upvotes: 4

Related Questions