首先说下js作用域链:由于js变量都是对象的属性,对象又可以是对象的属性,最终到达window,所以变量-------window就是一条作用域链;

先说下变量作用域:

var a=10;
function test(){
console.log(a);----------undefined
var a = 5;

console.log(a);----------5
}
test();

test() 方法内:console.log(a)中变量a寻找自己的定义,发现var a = 5;已经有定义了,所以a的定义就是局部变量。这个时候由于console.log(a)的时候a还没有被赋值,所以undefined

 

再看this:

var a=10;
function test(){

console.log(a);
this.a = 5;
var a =5;

}

test();---undefined
console.log(a);------5

this发现基本上都是指向window,都会改变全局变量。

除了

var a=10;
function test(){

console.log(a);
this.a = 5;


}

var t = new test(); ------10
console.log(a);---10

这个时候 this 属于函数t--不会改变全局变量

 

posted on 2015-09-23 15:05  前端小菜j  阅读(228)  评论(0编辑  收藏  举报