代码之家  ›  专栏  ›  技术社区  ›  Andrew Li

javascript回调函数类型:function()vs()=>[重复]

  •  2
  • Andrew Li  · 技术社区  · 8 年前

    我有一些关于jquery中回调函数类型的问题。
    我对javascript不太了解。
    这里是文档级的简单代码。

    $("input").change(function(){
      console.log(this);
    });  
    

    $("input").change(()=>{
      console.log(this);
    });
    

    这些日志结果如下。
    第一个控制台日志是激发更改事件的输入的对象。
    第二个是整个文档。 function()和()=>{}有什么区别?
    请帮帮我。
    谢谢。
    我附加了简单的测试源代码。

    <html>
    
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <script>
      $(document).ready(function(){
    	console.log("init");
    	$(".first").change(function(){
    		console.log(this);
    	});
    	$(".second").change(()=>{
    		console.log(this);
    	});
      });
    </script>
    </head>
    <body>
        <input type="text" class="first" />
        <input type="text" class="second" />
    </body>
    </html>
    1 回复  |  直到 8 年前
        1
  •  1
  •   TwiN Alireza Fattahi    8 年前

    正确的术语 ()=>{} 箭头函数 ,有时也称为 胖箭头函数 .

    箭头函数表达式的语法比函数短 表达式没有自己的this、arguments、super或 新目标。这些函数表达式最适合于非方法 函数,它们不能用作构造函数。

    reference

    另外,请参见 Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

    为了更深入地解释几个例子,您可以阅读 this article .