在JavaScript的大千世界中,this对象就像一个行踪不定、居无定所的浪子通常,它的生活仿佛能够随处而安,而心里却又似有着笃定的坚守,它就是这么有趣!javascript
初学JavaScript时的咱们,多多少少都拜访过this,却又老是找不许时机,屡屡与其擦肩而过。其实this一直就在那里,不离不弃。java
咱们要记住一句话:this永远指向函数运行时所在的对象!而不是函数被建立时所在的对象。切记…闭包
本文将分三种状况来分析this对象到底身处何方。app
不管this身处何处,第一要务就是要找到函数运行时的位置。函数
var name="全局"; function getName(){ var name="局部"; return this.name; }; alert(getName());
当this出如今全局环境的函数getName中时,此时函数getName运行时的位置在this
alert(getName());对象
显然,函数getName所在的对象是全局对象,即window,所以this的安身之处定然在window。此时的this指向window对象,则getName返回的this.name实际上是window.name,所以alert出来的是“全局”!blog
那么,当this不是出如今全局环境的函数中,而是出如今局部环境的函数中时,又会身陷何方呢?ip
var name="全局"; var twobin={ name:"局部", getName:function(){ return this.name; } }; alert(twobin.getName());
其中this身处的函数getName不是在全局环境中,而是处在twobin环境中。不管this身处何处,必定要找到函数运行时的位置。此时函数getName运行时的位置get
alert(twobin.getName());
显然,函数getName所在的对象是twobin,所以this的安身之处定然在twobin,即指向twobin对象,则getName返回的this.name实际上是twobin.name,所以alert出来的是“局部”!
闭包也是个不安分子,本文暂且不对其过于赘述,简而言之:所谓闭包就是在一个函数内部建立另外一个函数,且内部函数访问了外部的变量。
浪子this与痞子闭包混在一块儿,可见将永无宁日啊!
var name="全局"; var twobin={ name:"局部", getName:function(){ return function(){ return this.name; }; } }; alert(twobin.getName()());
此时的this明显身处困境,居然处在getName函数中的匿名函数里面,而该匿名函数又调用了变量name,所以构成了闭包,即this身处闭包中。
不管this身处何处,必定要找到函数运行时的位置。此时不能根据函数getName运行时的位置来判断,而是根据匿名函数的运行时位置来判断。
function (){
return this.name;
};
显然,匿名函数所在的对象是window,所以this的安身之处定然在window,则匿名函数返回的this.name实际上是window.name,所以alert出来的就是“全局”!
那么,如何在闭包中使得this身处在twobin中呢?
var name="全局"; var twobin={ name:"局部", getName:function(){ var that=this; return function(){ return that.name; }; } }; alert(twobin.getName()());
在getName函数中定义that=this,此时getName函数运行时位置在
alert(twobin.getName());
则this指向twobin对象,所以that也指向twobin对象。在闭包的匿名函数中返回that.name,则此时返回的that.name实际上是twobin.name,所以就能够alert出来 “局部”!
在JavaScript中能管的住this的估计也就非call与apply莫属了。
call与apply就像this的父母通常,让this住哪它就得住哪,不得不听话!
var name="全局"; var twobin={ name:"局部", }; function getName(){ alert(this.name); } getName(twobin); getName.call(twobin);
其中this身处函数getName中。不管this身处何处,必定要找到函数运行时的位置。此时函数getName运行时的位置
getName(twobin);
显然,函数getName所在的对象是window,所以this的安身之处定然在window,即指向window对象,则getName返回的this.name实际上是window.name,所以alert出来的是“全局”!
那么,该call与apply登场了,由于this必须听他们的指挥!
getName.call(twobin);
其中,call指定this的安身之处就是在twobin对象,由于this被迫只能在twobin那安家,则此时this指向twobin对象, this.name实际上是twobin.name,所以alert出来的是“局部”!
浪子this:永远指向函数运行时所在的对象,而不是函数被建立时所在的对象;若是处在匿名函数中或不处于任何对象中,则this指向window对象;若是是call或apply,它指定哪一个对象,则this就指向哪一个对象!