JavaScript 箭头函数
- 上一页 JS this 关键词
- 下一页 JS 类
Arrow functions were introduced in ES6.
Arrow functions allow us to write shorter functions:
Grammar
let myFunction = (a, b) => a * b;
Before:
hello = function() { return "Hello World!"; }
After using arrow function:
hello = () => { return "Hello World!"; }
It really got shorter! If the function has only one statement and the statement returns a value, you can remove the parentheses and return
Keyword:
Default return value of arrow function:
hello = () => "Hello World!";
Note:This only works if the function has only one statement.
If you have parameters, pass them into the parentheses:
Arrow function with parameters:
hello = (val) => "Hello " + val;
In fact, if there is only one parameter, you can also omit the parentheses:
Arrow function without parentheses:
hello = val => "Hello " + val;
this
What should I do?
Compared to conventional functions, arrow functions have this
is also different.
In short, using arrow functions does not have the same handling for this
binding.
In conventional functions, the keyword this
represents the object that calls the function, which can be a window, document, button, or anything else.
For arrow functions,this
The keyword always represents the object that defines the arrow function.
Let's look at two examples to understand the difference.
These two examples call the method twice, once when the page loads and once when the user clicks the button.
The first example uses a conventional function, and the second example uses an arrow function.
The result shows that the first example returns two different objects (window and button), and the second example returns two window objects because the window object is the 'owner' of the function.
instance
For conventional functions, this represents the object that calls the function:
// conventional function: hello = function() { document.getElementById("demo").innerHTML += this; } // window 对象调用该函数: window.addEventListener("load", hello); // button 对象调用该函数: document.getElementById("btn").addEventListener("click", hello);
instance
used arrow function, then this
表示函数的拥有者:
// 箭头函数: hello = () => { document.getElementById("demo").innerHTML += this; } // window 对象调用该函数: window.addEventListener("load", hello); // button 对象调用该函数: document.getElementById("btn").addEventListener("click", hello);
使用函数时请记住这些差异。有时,常规函数的行为正是您想要的,如果不是,请使用箭头函数。
浏览器支持
下表注明了首个完全支持 JavaScript 箭头函数的浏览器版本:
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 45 | Edge 12 | Firefox 22 | Safari 10 | Opera 32 |
2015 年 9 月 | 2015 年 7 月 | 2013 年 5 月 | 2016 年 9 月 | 2015 年 9 月 |
- 上一页 JS this 关键词
- 下一页 JS 类