JavaScript基本知识——变量作用域,全局变量和局部变量

JavaScript基本知识——变量作用域

一、this指向作用域

    this指向函数运行时所在的环境。函数所处的环境与对象地址有关,例如show()所处的环境是window,因为直接定义的函数默认挂载到window对象里,可以通过window属性访问。而b=a.show其实b指向的也是一个地址,即函数对象本身。

var title="world";
var a={
	alias:this.title,
	title:"hello",
	show:function(){
		console.log(this.title);
		console.log(this.alias);
	},
	display: () =>{
		console.log(this.title);
		console.log(this.alias);
	}
}
a.show();
var b=a.show;
b();
a.display();

二、全局变量

  1. 以下代码输出结果为10,20,10
var a = 20;
function test(){
    a = 10;
    console.log(a);
    console.log(this.a);
    var a;
    console.log(a);
}
test();
  1. 以下代码输出结果为 undefined,20,10
var a = 20;
function test(){
    console.log(a);
    console.log(this.a);
    var a=10;
    console.log(a);
}
test();
  1. 以下代码输出结果为 20,20,10
var a = 20;
function test(){
    console.log(a);
    console.log(this.a);
   	a=10;
    console.log(a);
}
test();

声明提前:javascript脚本在运行时先解析函数的声明的变量,运行时执行代码。javascript在非严格模式下没有用var定义变量时默认定义成全局变量(var a=b=1,b是全局变量,a是局部变量),在function用var定义的变量是局部变量存在栈中运行完立即销毁。

三、匿名函数

立即执行的匿名函数不会污染全局变量,像jquery是用这种方式定义的。

(function (a, b) {
   // jquery code
})(window);

以下代码运行结果为20,20,10

var a = 20;
(function test(){
    console.log(a);
    console.log(this.a);
   	a=10;
    console.log(a);
})()

后续持续更新。。。

猜你喜欢

转载自blog.csdn.net/qq_29510269/article/details/88937723