创建“命名空间";在$(document).ready(function(){..})中; [英] Create "namespace" in $(document).ready(function() {..});

查看:81
本文介绍了创建“命名空间";在$(document).ready(function(){..})中;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// first.js
$(document).ready(function() {
   var MyNamespace = {};
});

// second.js
$(document).ready(function() {
   console.log(MyNamespace);
});

运行此脚本时,出现错误Uncaught ReferenceError: MyNamespace is not defined.我想,我收到此错误是因为MyNamespaceMyNamespace调用的定义在不同的范围内.我该如何解决这个问题?

Running this script I'm getting error Uncaught ReferenceError: MyNamespace is not defined. I suppose, I'm getting this error because definition of MyNamespace and MyNamespace calling are in different scopes. How do I solve this problem?

我需要在$(document).ready()包装器内创建名称空间,因为该名称空间中的函数将使用jQuery方法等.

I need to create namespace inside $(document).ready() wrapper because functions in this namespace will use jQuery methods etc.

最佳做法是什么?

谢谢!

推荐答案

您需要更改两件事:

  1. MyNamespace放在全局范围内;
  2. 避免在每个文件中重新定义 MyNamespace
  1. Put the MyNamespace in a global scope;
  2. Avoid redefining MyNamespace in each file;

您将var MyNamespace = MyNamespace || {};放在两个js文件的前面.如果以前没有定义,它将把MyNamespace当作一个对象来代替.

You put var MyNamespace = MyNamespace || {}; in front of both your js files. It decalres MyNamespace as an object if it isn't defined before.

// first.js
var MyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});

// second.js
var MyNamespace = MyNamespace || {};
$(document).ready(function() {
   console.log(MyNamespace);
});

这篇关于创建“命名空间";在$(document).ready(function(){..})中;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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