简体   繁体   English

无法访问另一个javascript文件中的变量

[英]can't access variables in another javascript file

So i have link every file needed into the index.html file : 所以我将所需的每个文件链接到index.html文件中:

    <script src="jquery.js"></script>
    <script src="notify.js"></script>
    <script src="script.js"></script>

i create an object in 'notify.js' : 我在'notify.js'中创建了一个对象:

    var notify = {
    newNotification : function(text) {
    }
}

script.js : script.js:

alert(notify.newNotification);

When i try to access the 'notify' object in 'script.js', it works just fine.But i want to use jquery so i add $(document).ready() to both of the file like this: 当我尝试访问'script.js'中的'notify'对象时,它工作正常。但我想使用jquery所以我将$(document).ready()添加到这两个文件中:

notify.js notify.js

    $(document).ready (
    function() {
var notify = {
    newNotification : function(text) {
    }
}
}
)

Script.js: 的script.js:

    $(document).ready (
    function() {
alert(notify.newNotification);
    }
)

And after i add that, it comes up with notify is not defined.What's wrong? 在我添加之后,它提出了未定义的通知。出了什么问题? Can anyone explain why it doesn't work? 任何人都可以解释为什么它不起作用?

As you have defined var notify in notify.js inside $(document).ready( which is an anonymous function and var notify scope is limited to this function only . 正如您在$(document).ready(中的notify.js中定义了var notify $(document).ready(这是一个匿名函数, var notify scope仅限于此函数。

So it is not accessible outside the $(document).ready( function 所以它不能在$(document).ready(函数

To make accessible outside don't wrap it in $(document).ready( function 要在外部访问,请不要将其包装在$(document).ready( function

like this:- 像这样:-

var notify;
$(document).ready(function () {
    notify = {
        newNotification: function (text) { }
    }
});

Like everyone else here already pointed out: Only use $().ready when you're handling DOM-Elements and your Variable is not accessible because you used the var keyword (like you're supposed to). 就像这里已经指出的其他人一样:只有在处理DOM-Elements时才使用$().ready并且因为你使用了var关键字(就像你应该的那样)而无法访问你的Variable。 The var keyword limits the defined variables to the current scope, which is the scope of the anonymous function you use as your DOM-Ready-Handler. var关键字将定义的变量限制为当前作用域,这是您用作DOM-Ready-Handler的匿名函数的作用域。

So, removing the unnecessary $().read will temporary solve your problem. 因此,删除不必要的$().read将暂时解决您的问题。

BUT(!) you should wrap your code into a closures to avoid messing up the global scope and to avoid possible naming conflicts with 3rd-party code. 但是(!)您应该将代码封装到闭包中以避免弄乱全局范围并避免与第三方代码发生可能的命名冲突。

Like that: 像那样:

notify.js notify.js

;(function ($, window, undefined) {
  var notify = {
    newNotification : function(text) {
      return text;
    }
  };
})(jQuery, this);

script.js 的script.js

;(function ($, window, undefined) {
  alert(notify.newNotification());
})(jQuery, this);

So, now you'll have the same problem as before, you don't have access to your Object. 因此,现在您将遇到与以前相同的问题,您无权访问您的对象。

Sure you could just add your notify Object to the global scope as Arun P Johny suggested in his answer, but i'm pretty sure over the time there will be more Object you'll need to make global accessible. 当然,您可以将您的notify对象添加到全局范围,正如Arun P Johny在他的回答中所建议的那样,但我非常确定当时会有更多的对象需要全局访问。 If you put each of them in the global scope, you start messing up the global scope again, so my recommendation would be ONE global Object that will hold all other objects/variables you need globally accessible. 如果将它们中的每一个放在全局范围内,则会再次开始弄乱全局范围,因此我的建议是一个全局对象,它将保存您需要全局访问的所有其他对象/变量。 (Or even better use something like requirejs (或者甚至更好地使用像requirejs这样的东西

Somethink like this: 有人这样想:

main.js main.js

;var MyApp = {}; # Only variable in global scope

# Maybe some more initalization code here, dunno

notify.js notify.js

;(function ($, window, undefined) {
  MyApp.notify = {
    newNotification : function(text) {
      return text;
    }
  };
})(jQuery, this);

script.js 的script.js

;(function ($, window, undefined) {
  alert(MyApp.notify.newNotification());
})(jQuery, this);

Some interesting Q/A's about scope and closures here on stackoverflow: 关于stackoverflow的范围和闭包的一些有趣的Q / A:

A good Answer about messing around with the global scope: 关于搞乱全球范围的一个很好的答案:

In this case there is no need to wrap the notification object in dom ready... because from the looks of it you are not creating any dom element reference while creating the object... the only thing that matters is any method invokation that deals with dom element has to be done on dom ready. 在这种情况下,没有必要将通知对象包装在dom中...因为从它的外观来看,你在创建对象时没有创建任何dom元素引用...唯一重要的是任何方法调用处理dom元素必须在dom准备就绪。

var notify = {
    newNotification: function (text) {}
}

$(document).ready(function () {
    notify.newNotification()
})

if you declare the variable inside a dom ready handler then it becomes a local variable to the dom ready handler... so it will not be accessible outside the dom ready handler... 如果你在dom ready处理程序中声明变量,那么它就成为dom ready处理程序的局部变量...所以它不能在dom ready处理程序之外访问...

Another solution is to add the variable to the global scope within the dom ready handle like 另一种解决方案是将变量添加到dom ready句柄中的全局范围中

var notify;
$(document).ready(function () {
    notify = {
        newNotification: function (text) {}
    }
})

or 要么

$(document).ready(function () {
    window.notify = {
        newNotification: function (text) {}
    }
})

You only need one document.ready And this only declare the variables that will move freely in their scripts. 您只需要一个document.ready而这只会声明将在其脚本中自由移动的变量。

See the example: 看例子:

script.js: 的script.js:

$(document).ready(function(){
   // declare the variables as global
   $.varA, $.varB, $.varC;
});

notify.js: notify.js:

function doNotify(){
   // your code here
   $.varA = /*your code here */
}

function otherFunc(txt){
   // your code here
   $.varB = txt;
}

All of your JavaScripts will load before the document is ready. 在文档准备好之前,将加载所有JavaScripts。

Create a separate function in script.js that references the notify object, then call that function from $(document).ready script.js中创建一个引用notify对象的单独函数,然后从$(document).ready调用该函数

Try this. 尝试这个。

var notify = {
    newNotification : function(text) {
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM