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 這個對象。