[英]can't access variables in another javascript file
所以我将所需的每个文件链接到index.html文件中:
<script src="jquery.js"></script>
<script src="notify.js"></script>
<script src="script.js"></script>
我在'notify.js'中创建了一个对象:
var notify = {
newNotification : function(text) {
}
}
script.js:
alert(notify.newNotification);
当我尝试访问'script.js'中的'notify'对象时,它工作正常。但我想使用jquery所以我将$(document).ready()添加到这两个文件中:
notify.js
$(document).ready (
function() {
var notify = {
newNotification : function(text) {
}
}
}
)
的script.js:
$(document).ready (
function() {
alert(notify.newNotification);
}
)
在我添加之后,它提出了未定义的通知。出了什么问题? 任何人都可以解释为什么它不起作用?
正如您在$(document).ready(
中的notify.js中定义了var notify
$(document).ready(
这是一个匿名函数, var notify
scope仅限于此函数。
所以它不能在$(document).ready(
函数
要在外部访问,请不要将其包装在$(document).ready(
function
像这样:-
var notify;
$(document).ready(function () {
notify = {
newNotification: function (text) { }
}
});
就像这里已经指出的其他人一样:只有在处理DOM-Elements时才使用$().ready
并且因为你使用了var
关键字(就像你应该的那样)而无法访问你的Variable。 var关键字将定义的变量限制为当前作用域,这是您用作DOM-Ready-Handler的匿名函数的作用域。
因此,删除不必要的$().read
将暂时解决您的问题。
但是(!)您应该将代码封装到闭包中以避免弄乱全局范围并避免与第三方代码发生可能的命名冲突。
像那样:
notify.js
;(function ($, window, undefined) {
var notify = {
newNotification : function(text) {
return text;
}
};
})(jQuery, this);
的script.js
;(function ($, window, undefined) {
alert(notify.newNotification());
})(jQuery, this);
因此,现在您将遇到与以前相同的问题,您无权访问您的对象。
当然,您可以将您的notify
对象添加到全局范围,正如Arun P Johny在他的回答中所建议的那样,但我非常确定当时会有更多的对象需要全局访问。 如果将它们中的每一个放在全局范围内,则会再次开始弄乱全局范围,因此我的建议是一个全局对象,它将保存您需要全局访问的所有其他对象/变量。 (或者甚至更好地使用像requirejs这样的东西
有人这样想:
main.js
;var MyApp = {}; # Only variable in global scope
# Maybe some more initalization code here, dunno
notify.js
;(function ($, window, undefined) {
MyApp.notify = {
newNotification : function(text) {
return text;
}
};
})(jQuery, this);
的script.js
;(function ($, window, undefined) {
alert(MyApp.notify.newNotification());
})(jQuery, this);
关于stackoverflow的范围和闭包的一些有趣的Q / A:
关于搞乱全球范围的一个很好的答案:
在这种情况下,没有必要将通知对象包装在dom中...因为从它的外观来看,你在创建对象时没有创建任何dom元素引用...唯一重要的是任何方法调用处理dom元素必须在dom准备就绪。
var notify = {
newNotification: function (text) {}
}
$(document).ready(function () {
notify.newNotification()
})
如果你在dom ready处理程序中声明变量,那么它就成为dom ready处理程序的局部变量...所以它不能在dom ready处理程序之外访问...
另一种解决方案是将变量添加到dom ready句柄中的全局范围中
var notify;
$(document).ready(function () {
notify = {
newNotification: function (text) {}
}
})
要么
$(document).ready(function () {
window.notify = {
newNotification: function (text) {}
}
})
您只需要一个document.ready而这只会声明将在其脚本中自由移动的变量。
看例子:
的script.js:
$(document).ready(function(){
// declare the variables as global
$.varA, $.varB, $.varC;
});
notify.js:
function doNotify(){
// your code here
$.varA = /*your code here */
}
function otherFunc(txt){
// your code here
$.varB = txt;
}
在文档准备好之前,将加载所有JavaScripts。
在script.js
中创建一个引用notify
对象的单独函数,然后从$(document).ready
调用该函数
尝试这个。
var notify = {
newNotification : function(text) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.