js作用域问题 var scope = "global";function test(){ alert(scope); //undefined? var scope = "local"; alert(scope); //local}test();请问为什么第一个alert输出的是undefined,而不是global呢? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 js在函数里定义的变量可以在函数里的任意位置访问,甚至定义前的位置 你的方法其实函数里定义的scope已经在方法里覆盖掉了外边的scope 而此时scope又没赋值 所以undefined 以后这样写function test(){var scope = "local"; alert(scope); //undefined? alert(scope); //local}不要这样写function test(){ alert(scope); //undefined? var scope = "local"; alert(scope); //local}何必自扰 var scope = "global";function test(){ alert(scope); //undefined? var scope = "local"; alert(scope); //lcal}test();因为函数外面的那个叫全局变量,函数内部的叫局部变量,函数内部局部变量最大,因此它会覆盖掉全局变量。你写的内部函数相当于;var scope;alert(scope);scope="local";alert(local);参见JS权威指南第6版,你这个例子就是里面的。 几个常识问题! 关于一段Javascript在html里面重复执行的问题求助 提示form未定义 错误 可算明明已经给form定义名字了啊 用javascript做多级菜单思路? 关于数组的问题 用图片代替上传按钮代码,请大家帮忙改写得更通用.谢谢 请高手看看怎样利用百度地图实现 怎样得到FORM里的对象集合,及此集合的长度 JS中请教对字符串的处理,如何删除、替换指定的字符串?感激不尽! 如何在页面中如何动态增加控件,并且控件的名称也动态的变换呢? (100分),刚学习的js,挺麻烦的!!半小时后结贴,多谢! jQuery新加载的元素怎样绑定事件
你的方法其实函数里定义的scope已经在方法里覆盖掉了外边的scope 而此时scope又没赋值 所以undefined
function test(){
var scope = "local";
alert(scope); //undefined?
alert(scope); //local
}
不要这样写
function test(){
alert(scope); //undefined?
var scope = "local";
alert(scope); //local
}
何必自扰
var scope = "global";function test(){
alert(scope); //undefined?
var scope = "local";
alert(scope); //lcal
}test();因为函数外面的那个叫全局变量,函数内部的叫局部变量,函数内部局部变量最大,因此它会覆盖掉全局变量。
你写的内部函数相当于;
var scope;
alert(scope);
scope="local";
alert(local);
参见JS权威指南第6版,你这个例子就是里面的。