0

I am creating some basic plugin and i am getting Reference error. Below is my code

jQuery.fn.validate = function(options) {
  var _self = this;
   // with below call I gets reference error.
  abc();  

    //but if call in below it works fine
  _self.on("submit", function(event) {
     abc();  // works fine
  }),

 abc = function () {
   console.log('here);
 }
};

Can someone explain why I am getting this error and how to overcome it. As i need to call some reset and init functions at the begining of the plugin.

Aman jaura
  • 201
  • 3
  • 15

1 Answers1

1

It seems like you're expecting abc to be hoisted, but you're specifically using a syntax that leaves abc undefined until the assignment is executed.

You need to move abc = function ... up above the invocations of abc(), or define the function using function abc() { } which will allow it to be hoisted above your invocations.

Note that, if you simply move the assignment, you should use var abc = function ... and create a local variable, rather than the global abc variable you're currently creating.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • ok i got your point but it works when i call _self.on("submit", function(event) { abc(); // works fine }), – Aman jaura Mar 29 '18 at 20:05
  • @Amanjaura Because that is invoked after your assignment, at some point in the future when a button is clicked and that callback is invoked. – user229044 Mar 29 '18 at 20:06
  • So which approach should i use in plugins while creating function `abc = functions` or `function abc()` ? Or is there any better solution on how to create and initialize functions in js plugin. Anyhow thanks for the above explanation. – Aman jaura Mar 29 '18 at 20:10