Javascript - 在document.ready中更改全局变量?

时间:2017-07-10 03:15:16

标签: javascript global document-ready

我有一个全局变量numberOfMessages,我希望根据对可靠性合同的调用带回来立即设置为特定数字。在加载页面时,在document.ready函数中进行调用。但是,变量在此功能之外不会更改。

我的代码基本上是这样的:

var numberOfMessages = 0 // declared outside any function, so should be global
$(document).ready(function () {
Message.deployed().then(function (contractInstance) {
    contractInstance.getNumberMessages.call().then(function (v) {
      numberOfMessages = v
      alert(numberOfMessages) // returns something other than 0
    })
  })
})
alert(numberOfMessages) // returns 0

如何设置一个全局变量,该变量设置为加载页面时函数返回的内容?

3 个答案:

答案 0 :(得分:2)

你的最后一行是在承诺'.then()异步回调之外运行的。这意味着在文档就绪之前运行的最后一行甚至会在异步调用完成之前触发

另外,不要使用alert()来测试代码,因为这样的提示通常是阻塞的,这意味着暂停代码执行并且可以使用异步回调执行奇怪的操作。而是使用console.log()并在浏览器的Javascript控制台中查看结果(通常通过按F12打开)。

答案 1 :(得分:-1)

尝试删除

var numberOfMessages = 0

在第一行。如果为尚未声明的变量赋值,它将自动成为GLOBAL变量。

答案 2 :(得分:-1)

根据其他几个类似的问题,我可以说你的变量是window.numberOfMessages = 0

  

#3 window.a = 0;

     

使用。显式创建全局对象的属性   window global指的是全局对象(在浏览器上;有些   非浏览器环境具有等效的全局变量,例如   NodeJS上的全局)。因为它是普通的属性,你可以删除它。

     

此属性可在 IE8 和更早版本以及其他所有内容中枚举   浏览器我试过了。

以上分类由here发布,并为您解释什么是全局范围变量和全局显式变量。

window.numberOfMessages = 0 // This creates a property on the global object explicitly
$(document).ready(function() {
  Message.deployed().then(function(contractInstance) {
    contractInstance.getNumberMessages.call().then(function(v) {
      window.numberOfMessages= v
      console.log(window.numberOfMessages) // returns something other than 0
    })
  })
})
console.log(window.numberOfMessages) // returns 0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>