[英]JavaScript Global Variable Assignment
I had written a code as shown, where I was assigning a global variable a value, which suspended my further code execution. 我编写了如下所示的代码,在其中为全局变量分配了一个值,这暂停了我进一步的代码执行。
resultCollection is the global variable. resultCollection是全局变量。 Also my program is running in strict mode. 我的程序也在严格模式下运行。
"use strict";
var View = Backbone.View.extend({
initialize : function(options){
this.el = options.el;
resultCollection = options.resultCollection;
console.log('resultCollection',resultCollection);
this.render();
}
The console.log was never printed and the execution doesn't stop, just suspends or still executing when the global variable was assigned a value. 在向全局变量分配值时,从不打印console.log并且执行不会停止,只是挂起或仍在执行。
Why did this happen ? 为什么会这样呢? Can anyone give me some insight ? 谁能给我一些见识?
In the strict mode you should have seen the error in console. 在严格模式下,您应该已经在控制台中看到错误。
So prepend your variable name with window.
因此,在变量名前添加window.
and it will work. 它会工作。
PS: see http://jsfiddle.net/zerkms/6M3HM/ PS:参见http://jsfiddle.net/zerkms/6M3HM/
In console you would get Uncaught ReferenceError: b is not defined
, whereas global a
was defined well. 在控制台中,您将收到Uncaught ReferenceError: b is not defined
,而全局a
定义良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.