Mr.Gomer
Mr.Gomer

Reputation: 649

Understanding object creation in JavaScript

can some one plz explain why i have to declare formhandler like this ?

var FormHandler = App.FormHandler; //Like Java just putting a type to the variable.

var formHandler = new FormHandler(FORM_SELECTOR);

And why i cant just declare it like this.

var formHandler = new FormHandler(FORM_SELECTOR);

Why is the first line needed?

Here is the full FormHandler code in case it is needed to answer the question.

(function (window){
'use strict';
var App = window.App || {};
var $ = window.jQuery;

function FormHandler(selector) {
if(!selector) {
  throw new Error('No selector provided');
}

this.$formElement = $(selector);
if(this.$formElement.length === 0){
  throw new Error('Could not find element with selector: ' + selector);
 }
}

FormHandler.prototype.addSubmitHandler = function(fn) {
console.log('Setting submit handler for form');
this.$formElement.on('submit', function(event){
  event.preventDefault();

  
  var data = {};
  $(this).serializeArray().forEach(function(item) {
    data[item.name] = item.value;
    console.log(item.name + ' is ' + item.value);
  });
     console.log(data);
     fn(data);
    });
  };

  App.FormHandler = FormHandler;
  window.App = App;
 })(window);

Upvotes: -1

Views: 66

Answers (1)

Klaycon
Klaycon

Reputation: 11080

FormHandler doesn't exist in the global context (which is window in this case) because it was never assigned to it.

App does exist in the global context due to the line window.App = App.

So in your script you can just toss out App and it will find it on window.App but if you toss out FormHandler without defining it then it won't find anything and will cause a reference error.

If you need to make a FormHandler you must reference App.FormHandler. But the way you've written it is extraneous, it can just be done like this:

var formHandler = new App.FormHandler(FORM_SELECTOR);

Upvotes: 4

Related Questions