问题描述
// first.js
$(document).ready(function() {
var MyNamespace = {};
});
// second.js
$(document).ready(function() {
console.log(MyNamespace);
});
运行此脚本时,出现错误Uncaught ReferenceError: MyNamespace is not defined
.我想,我收到此错误是因为MyNamespace
和MyNamespace
调用的定义在不同的范围内.我该如何解决这个问题?
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.
最佳做法是什么?
谢谢!
推荐答案
您需要更改两件事:
- 将
MyNamespace
放在全局范围内; - 避免在每个文件中重新定义
MyNamespace
;
- Put the
MyNamespace
in a global scope; - 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(){..})中;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!