2017-05-26 7 views
2

背景jQueryの:()=> {}を使用し、機能()構文、後者の作品

私はjQueryのに行くを与えていると時間のために、私は$([selector]).hide([milliseconds])を使用して要素を隠すことができなかった、これ私のサンプルコードでは、要素、この場合はアンカータグ<a>をクリックすると呼び出されます。しかし、私は最終的にそれを働かせましたが、私は理由を理解していません。私が代わりに、functionキーワードを使用して行うために必要な唯一の変更なので、この:

thisない "A" 使用例として、編集この

function(event){ 
$(this).hide(2000); 
} 

event => { 
$(this).hide(2000); 
} 

を見ます

質問

機能の使用と矢印機能を使用するのはなぜですか?両者に違いはありますか?

私のテストのためのソースコードは、:

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Demo</title> 
    <style> 
    a.test{ 
     font-weight: bold; 
    } 
    </style> 
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script> 
    <!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>--> 
</head> 
<body> 
    <a href="http://jquery.com/">jQuery</a> 
    <script> 
     // $(document).ready(function() { 
     //  // $("a").click(event => { 
     //  //  alert("Thanks for visiting!"); 
     //  //  //prevents the opening of the link (what are the default events of other events types?) 
     //  //  event.preventDefault(); 
     //  //  //Special Effects - http://api.jquery.com/category/effects/ 
     //  // }); 

     // }); 
     $("a").click(function(event){ 
      event.preventDefault(); 
      $(this).hide(2000); 
     }); 
     $("a").addClass("test"); 
    </script> 
</body> 
</html> 
+0

あなたは、このような 'イベント=> $(この).hide(2000)'として、 'あなたの矢印関数内this'を使用しましたか?その場合は、https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6 –

+1

'function(event)=> { $(" a " ).hide(2000); } 'それは間違って見える –

+0

おっと、そう、私はその部分に=を付けずにそれを意味しました。ありがとう – ManWithAComputor

答えて

3

アロー機能はthisにつなが新しいスコープを作成しません。ですから、これを回避するには、通常の関数を使用してください(以下のように)。また、矢印の機能の内側に$(event.currentTarget).hide(2000);を入れることもできます。

<!doctype html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <title>Demo</title> 
 
    <style> 
 
    a.test{ 
 
     font-weight: bold; 
 
    } 
 
    </style> 
 
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script> 
 
    <!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>--> 
 
</head> 
 
<body> 
 
    <a href="http://jquery.com/">jQuery</a> 
 
    <script> 
 
     $("a").click(function(event) {$(this).hide(2000)}); 
 
     $("a").addClass("test"); 
 
    </script> 
 
</body> 
 
</html>

+0

'矢印機能はこれに繋がれた新しいスコープを作成しません - 'これは現在のイベントを参照していますか?私はこれが選択された要素を参照したと思った。 – ManWithAComputor

+0

私は今、矢印関数は独自の 'this'値を作成しません。代わりに、これは、それが入っている関数のスコープから継承した値を取得します。私の場合、これは' Window'オブジェクト矢印関数。 – ManWithAComputor

関連する問題