jQuery-$(document).ready()中的作用域? [英] jquery - scope inside $(document).ready()?

查看:239
本文介绍了jQuery-$(document).ready()中的作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保持井井有条,我有几个javascript文件,即使它们(最后)全部缩小在一起形成了一个最终的javascript文件.

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?

例如,在一个文件中,我有一堆代码来根据通过ajax接收的数据创建表.但是,文件的一半只是用于根据数据类型等显示数据的模板.我想将模板保存在自己的文件中.

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.

推荐答案

JavaScript使用函数作用域,因此函数内部的局部变量对外部不可见.这就是为什么您的代码无法从其他范围访问代码的原因.

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.

这篇关于jQuery-$(document).ready()中的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆