js this

在JavaScript的大千世界中,this对象就像一个行踪不定、居无定所的浪子一般,它的生活仿佛可以随处而安,而内心却又似有着笃定的坚守,它就是这么有趣!

初学JavaScript时的我们,多多少少都拜访过this,却又总是找不准时机,屡屡与其擦肩而过。其实this一直就在那里,不离不弃。

我们要记住一句话:this永远指向函数运行时所在的对象!而不是函数被创建时所在的对象。切记…

本文将分三种情况来分析this对象到底身处何方。

普通函数中的this

无论this身处何处,第一要务就是要找到函数运行时的位置。

1 var name="全局";
2 function getName(){
3     var name="局部";
4     return this.name;
5 };
6 alert(getName());

当this出现在全局环境的函数getName中时,此时函数getName运行时的位置在

alert(getName());

显然,函数getName所在的对象是全局对象,即window,因此this的安身之处定然在window。此时的this指向window对象,则getName返回的this.name其实是window.name,因此alert出来的是“全局”!

那么,当this不是出现在全局环境的函数中,而是出现在局部环境的函数中时,又会身陷何方呢?

复制代码
1 var name="全局";
2 var twobin={
3     name:"局部",
4     getName:function(){
5         return this.name;
6     }
7 };
8 alert(twobin.getName());
复制代码

其中this身处的函数getName不是在全局环境中,而是处在twobin环境中。无论this身处何处,一定要找到函数运行时的位置。此时函数getName运行时的位置

alert(twobin.getName());

显然,函数getName所在的对象是twobin,因此this的安身之处定然在twobin,即指向twobin对象,则getName返回的this.name其实是twobin.name,因此alert出来的是“局部”!

闭包中的this

闭包也是个不安分子,本文暂且不对其过于赘述,简而言之:所谓闭包就是在一个函数内部创建另一个函数,且内部函数访问了外部的变量。

浪子this与痞子闭包混在一起,可见将永无宁日啊!

复制代码
 1 var name="全局";
 2 var twobin={
 3     name:"局部",
 4     getName:function(){
 5         return function(){
 6             return this.name;
 7         };
 8     }
 9 };
10 alert(twobin.getName()());
复制代码

此时的this明显身处困境,竟然处在getName函数中的匿名函数里面,而该匿名函数又调用了变量name,因此构成了闭包,即this身处闭包中。

无论this身处何处,一定要找到函数运行时的位置。此时不能根据函数getName运行时的位置来判断,而是根据匿名函数的运行时位置来判断。

function (){

    return this.name;

};

显然,匿名函数所在的对象是window,因此this的安身之处定然在window,则匿名函数返回的this.name其实是window.name,因此alert出来的就是“全局”!

那么,如何在闭包中使得this身处在twobin中呢?

复制代码
 1 var name="全局";
 2 var twobin={
 3     name:"局部",
 4     getName:function(){
 5         var that=this;
 6         return function(){
 7             return that.name;
 8         };
 9     }
10 };
11 alert(twobin.getName()());
复制代码

在getName函数中定义that=this,此时getName函数运行时位置在

alert(twobin.getName());

则this指向twobin对象,因此that也指向twobin对象。在闭包的匿名函数中返回that.name,则此时返回的that.name其实是twobin.name,因此就可以alert出来 “局部”!

call与apply中的this

在JavaScript中能管的住this的估计也就非call与apply莫属了。

call与apply就像this的父母一般,让this住哪它就得住哪,不得不听话!

复制代码
1 var name="全局";
2 var twobin={
3     name:"局部",
4 };
5 function getName(){
6     alert(this.name);
7 }
8 getName(twobin);
9 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就指向哪个对象!

原文地址:https://www.cnblogs.com/step-by-step1/p/3413859.html