0

I got a javascript class with global variables and methods and a specefic method makes some extrange.

DOOM = (function () {
/** Class VALIDATIONS **/
var validation = function (form, inputDiv, action) {
    this.form = form;
    this.inputDiv = inputDiv; // -- This Variable
    this.action = action; // -- And This Variable
};
validation.prototype = {
    validate: function (rules, messages) {
        this.rules = rules;
        this.messages = messages;

        console.log(inputDiv);  // -- here still have value
        console.log(inputDiv);  

       $(this.form).validate({
            rules: this.rules,
            messages: this.messages,
            submitHandler: function(form){

                var getDom = new DOOM.DOM();
                var data = getDom.buildJSONValuesByJSON(getDom.buildJSONObjByForm(inputDiv)); // -- But here, already haven't value

                var sendData = new DOOM.callAJAX(action);
                sendData.start(data);

                console.log('[submitHandler] = '+ data);
                return false; 
            },

As workaround, I had to assign value where still the global variables has value. But my question is, Why those variables lost his values?.

Barmar
  • 741,623
  • 53
  • 500
  • 612
CR7
  • 69
  • 11

1 Answers1

2

Variables named in the parameter list of a function are always local variables, not global variables. So in the validation() constructor function, inputDiv is a local variable. If you're seeing something when you do console.log(inputDiv) in validation.prototype.validate(), it must be from a different variable declared outside the code that you posted.

To access the inputDiv that was provided to the constructor in the methods, you need to use this.inputDiv.

validation.prototype = {
    validate: function (rules, messages) {
        this.rules = rules;
        this.messages = messages;

        var inputDiv = this.inputDiv;

        console.log(inputDiv);

       $(this.form).validate({
            rules: this.rules,
            messages: this.messages,
            submitHandler: function(form){

                var getDom = new DOOM.DOM();
                var data = getDom.buildJSONValuesByJSON(getDom.buildJSONObjByForm(inputDiv));

                var sendData = new DOOM.callAJAX(action);
                sendData.start(data);

                console.log('[submitHandler] = '+ data);
                return false; 
            },
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Actually, I did like that . Thank you so much, for your explanation. Now I understand how works better these variables on javascript – CR7 Mar 03 '16 at 19:28