JS 函数(2)—this对象
this对象
this对象的指向是由它所在的函数的调用上下文决定的。
每个函数在被调用时,其活动对象会自动取得两个特殊变量,arguments和this;内部函数在搜索这个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量。也就是说,只会在匿名函数中,搜索this值,而匿名函数的this值通常指向window。
this对象是在运行时基于函数的执行环境绑定的:
在全局函数中,this等于window;
当函数被作为某个对象的方法调用时,this等于那个对象;
如果函数挂载在一个对象上,作为对象的一个属性,就称它为对象的方法;通过这个对象来调用函数时,该对象就是此次调用的上下文,也就是该函数的this值。
匿名函数的执行环境具有全局性,其this对象通常指向window;
关键字this没有作用域的限制,嵌套的函数不会从调用它的函数中继承this,如果嵌套函数作为方法调用,其this值不是全局对象(非严格模式下)就是undefined(严格模式下)。
如果想访问嵌套函数的外部函数的this值,需要将this的值保存在一个变量里,这个变量和内部函数在同一个作用域内。
在通过call()或者apply()方法改变函数执行环境的情况系,另行计较。
示例1:
1 var name = "The window"; 2 var object = { 3 name : "my object", 4 getNameFunc : function() { 5 return function() { 6 return this.name; 7 }; 8 } 9 }; 10 alert(object.getNameFunc()()); //"The window"
深度剖析:
1 var name = "The window"; 2 var object = { 3 name : "my object", 4 getNameFunc : function() { 5 return function() { 6 return this.name; 7 }; 8 } 9 }; 10 11 var temp = object.getNameFunc(); //此时并没有执行this.name 12 var name = temp(); //此时执行this.name,其上下文为全局,所以this指代window,返回"The window" //"my object" 13 console.log(name); //"The window" 14 console.log(object.getNameFunc()()); //"The window"
示例2:
1 var name = "The window"; 2 var object = { 3 name : "my object", 4 getNameFunc : function() { 5 var that = this; 6 return function() { 7 return that.name; 8 }; 9 } 10 }; 11 alert(object.getNameFunc()()); //"my object"
深度剖析:
1 var name = "The window"; 2 var object = { 3 name : "my object", 4 getNameFunc : function() { 5 var that = this; 6 return function() { 7 return that.name; 8 }; 9 } 10 }; 11 var temp = object.getNameFunc(); //执行that=this,这里的this指向的是object,所以that指向object 12 var name = temp(); //执行that.name,也就是object.name,所以返回"my object" 13 console.log(name); //"my object" 14 console.log(object.getNameFunc()());

浙公网安备 33010602011771号