0

What are the limitations/problems of binding a variable to the Jquery Object. I have a function in file A that I would like to access in file B. So in order to do that I bind it to the Jquery Object. I feel there might be reasons not to do that. But I can't think of any. Can anyone help me

e.g

    // File A
    $.sayHello = function sayHello(){
        alert("Hello");
    }

    //File B
    $.sayHello();

what are the problems with this.

2
  • You might overwrite an existing function. Also you will be polluting jQuery namespace. Commented Aug 23, 2016 at 16:17
  • api.jquery.com/jQuery.fn.extend Commented Aug 23, 2016 at 16:19

4 Answers 4

1

Problem with what you do is conflicting with existing functions, that is valid even if you not bind to jQuery and bind to your window, so its better to create namespace and attach variables, functions to it:

Myspace = {}
Myspace.sayHello = function sayHello(){
    alert("Hello");
}
Myspace.sayHello();

or if you still want to attach to jQuery do the same with jQuery:

$.Myspace = {}
$.Myspace.sayHello = function sayHello(){
    alert("Hello");
}
$.Myspace.sayHello();
Sign up to request clarification or add additional context in comments.

2 Comments

What you mention here is a good practice, not an answer for the question.
Yes, but that fix the issue from the start and remove any concerns to bind functions to jQuery
0

You have to ensure that FileA will load before FileB. If you can't ensure that, I'd recommend using document.ready to ensure that the method isn't called until all files are loaded.

// File A
$.sayHello = function sayHello(){
    alert("Hello");
}

//File B
$(document).ready(function() {
    $.sayHello();
});

Comments

0

Don't pollute the jQuery namespace, declare your own namespace instead :

var myNamespace;
(function (myNamespace) {
    var doSomething = function () { console.log('Did Something'); };
})(myNamespace || (myNamespace = {}));

Comments

0

I suggest to use mohamed-ibrahim solution with namespace but with jquery :

File A:

$.fn.extend({
  sayHello: function() {
    alert("Hello");
  }
});

File B :

$.fn.sayHello();

Without Jquery :

File A :

var MYNS = {
  sayHello: function(){
      console.log("Hello");
  }

}

File B :

MYNS.sayHello();

Make sure that file A is defined before file B

Comments

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.