首页 > Web开发 > 详细

js 变量作用域 与 this

时间:2015-09-23 16:54:30      阅读:180      评论:0      收藏:0      [点我收藏+]

首先说下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--不会改变全局变量

 

js 变量作用域 与 this

原文:http://www.cnblogs.com/qianduanxiaocaij/p/4832315.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!