Tips:我的博客:https://haonancx.github.io;排版更佳~git
要学同样东西,首先得了解它的含义,this 关键字的含义是明确且具体的,即指代当前对象;细心的童鞋发现了 当前对象 中"当前" 这两个字;说明这个 this 是在某种相对状况下才成立的。github
因为其运行期绑定的特性,JavaScript 中的 this 含义要丰富得多,它能够是全局对象、当前对象或者任意对象,这彻底取决于函数的调用方式。JavaScript 中函数的调用有如下几种方式:做为对象方法调用,做为函数调用,做为构造函数调用,和使用 apply 或 call 调用。下面咱们将按照调用方式的不一样,分别讨论 this 的含义。ruby
做为函数调用网络
做为对象方法调用app
做为构造函数调用函数
使用 apply 或 call 调用this
别急,咱一个萝卜一个坑,带你入坑之后,你就恍然大悟了。spa
废话少说,上个菜!!!code
{% highlight ruby %}对象
function example(){ this.n = 'hello world !'; console.log(this.n); console.log(this); } example(); // hello world ! Window
{% endhighlight %}
很显然,调用 example(); 时,输出了 'hello world !' 还有 Window;这时候说它是全局对象好像不具有什么说服力;咱换个姿式。
{% highlight ruby %}
var n = 'hello world !'; function example(){ console.log(this.n); } example(); // hello world !
{% endhighlight %}
你瞧,又是 ' hello world ! ',不急,咱有一千种姿式等你来解锁;再换。
{% highlight ruby %}
var n = 'hello world !'; function example(){ this.n = 0; } example(); console.log(n); // 0 !
{% endhighlight %}
果真是一辆 '公交车' !!!
{% highlight ruby %}
var name="Akita"; var dogs={ name:"Collie", showName:function(){ console.log(this.name); } } dogs.showName(); //输出 Collie var otherName=dogs.showName; otherName(); //输出 Akita
{% endhighlight %}
快来看,当执行 dogs.showName(); 时,输出 Collie (牧羊犬),说明这个时候的 This 是指向 dogs 这个对象的;
而当咱们尝试把 dogs.showName 赋给 otherName 时,咱们回头想一想这个 showName() 是作什么用的,很显然,输出它函数的执行环境所指向对象的 name,而此时 otherName 变量至关于 Window 对象的一个属性,所以 otherName() 执行的时候至关于 window.otherName(),即 window 对象调用 otherName 这个方法,因此 this 关键字指向 window;因此就会输出 Akita(秋田犬)。
{% highlight ruby %}
function example(){ this.n = 'hello world !'; } var other = new example(); console.log(other.n); //hello world !
{% endhighlight %}
快来看,咱们为 example 这个函数 new(构造)了一个新的对象 other,那么 this 就会指向 other 这个对象,因此就会输出 'hello world !'。
{% highlight ruby %}
var n = 'hello world!'; function example(){ console.log(this.n); } var o={}; o.n = 'hey~'; o.m = example; o.m.apply();//hello world!
{% endhighlight %}
来看看这行代码,当apply()的参数为空时,就是没有对象去替换掉当前的对象,因此默认调用全局对象。所以,这时会输出'hello world!',证实this指的是全局对象。
那么试试给apply()指定一个对象。
{% highlight ruby %}
var n = 'hello world!'; function example(){ console.log(this.n); } var o={}; o.n = 'hey~'; o.m = example; o.m.apply(o);//hey~
{% endhighlight %}
此时输出了'hey~',说明对象替换成功,this 指向了 o 这个对象。