343   JS

一,JS按照作用域分为两种变量:

关于定义

1,全局变量,在整个页面中的生命周期内都有效

2,局部变量,只在函数或者对象内部才有效

 

使用说明

1,如果变量声明时不带var,默认是全局变量;在对象内部声明的,并带有var都是局部变量

2,所有变量在JS执行时会全部放到头部进行定义

二,测试变量

 

1,全局变量

var t_1 = 1;
function test(){
	t_2 = 2;
	console.log('in function:'+t_1);
	console.log('in function:'+t_2);
}

test();
console.log('out function:'+t_1);
console.log('out function:'+t_2);

结果显示:

out function:1
out function:2
in function:1
in function:2

2,局部变量

function test(){
	var t_1 = 1;
	var t_2 = 2;
	console.log('in function:'+t_1);
	console.log('in function:'+t_2);
}

test();
console.log('out function:'+t_1);
console.log('out function:'+t_2);

结果显示

in function:1
in function:2
C:\Users\luckybird\Desktop\test\test.js:10
console.log('out function:'+t_1);
                            ^

ReferenceError: t_1 is not defined

显然外部无法调用函数内部的局部变量




Leave a Reply

Your email address will not be published. Required fields are marked *