Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

jquery - scope inside $(document).ready()?

So to stay organized, I have several javascript files, even though they all (in the end) are minified together to form one final javascript file.

Each file's contents are wrapped in:

$(document).ready(function(){
    //some javascript here
});

It seems like if I have things in separate files (in between that code) they don't have access to each other. Is this a scope issue? What can I do?

For example, in one file I had a bunch of code to create tables from data received through ajax. However, half of the file was just templates for how to display the data depending on it's types and such. I would like to have the templates in their own file.

I understand this is just a 'preference' issue and that I could just have it all in one file.

But I'm hoping to learn from this and perhaps even be able to have it 'my' way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Javascript uses functional scopes, so local variables inside a function are not visible to the outside. This is why your code can't access code from other scopes.

The ideal solution to this is create a Namespace.

var NS = {};

(function(){
  function privateFunction() { ... }
  NS.publicFunction = function(){ ... }
})();

$(document).ready(function(){
  NS.publicFunction();
});

This is also a useful pattern because it allows you to make a distinction between private & public elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...