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.

5
  • You're calling abc() before you have declared it, move the call to abc() below where you declare abc = function() Commented Mar 29, 2018 at 20:00
  • You shouldn't define global names in a plugin, you should make abc a local name. Commented Mar 29, 2018 at 20:02
  • 2
    Possible duplicate of var functionName = function() {} vs function functionName() {} Commented Mar 29, 2018 at 20:03
  • @Barmar what do you mean by local name ? Can you give me example ? Commented Mar 29, 2018 at 20:39
  • var abc = ... instead of just abc = ... Commented Mar 29, 2018 at 20:42

1 Answer 1

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.

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

3 Comments

ok i got your point but it works when i call _self.on("submit", function(event) { abc(); // works fine }),
@Amanjaura Because that is invoked after your assignment, at some point in the future when a button is clicked and that callback is invoked.
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.

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.