ES6 can use "arrow" (=>) to define functions. Note that they are functions, and do not use this method to define classes (constructors).
1. Syntax
1. A simple function with one parameter
var single = a => asingle('hello, world') // 'hello, world'2. If there are no parameters, you need to use brackets before the arrow.
var log = () => { alert('no param')}3. Multiple parameters require brackets, and comma intervals between parameters, such as adding two numbers
var add = (a, b) => a + badd(3, 8) // 11
4. Curly braces are required for multiple statements in function body
var add = (a, b) => { if (typeof a == 'number' && typeof b == 'number') { return a + b } else { return 0 }}5. When returning the object, you need to wrap it in brackets, because the braces are occupied and interpreted as code blocks.
var getHash = arr => { // ... return ({ name: 'Jack', age: 33 })}6. Directly as event handler
document.addEventListener('click', ev => { console.log(ev)})7. Sort callback as array
var arr = [1, 9 , 2, 4, 3, 8].sort((a, b) => { if (a - b > 0 ) { return 1 } else { return -1 }})arr // [1, 2, 3, 4, 8, 9]2. Pay attention
1. The typeof operator is the same as the ordinary function
var func = a => aconsole.log(typeof func); // "function"
2. instanceof also returns true, indicating that it is also an instance of Function
console.log(func instanceof Function); // true
3. This is fixed, no longer changeable
obj = { data: ['John Backus', 'John Hopcroft'], init: function() { document.onclick = ev => { alert(this.data) // ['John Backus', 'John Hopcroft'] } // non-arrow function // document.onclick = function(ev) { // alert(this.data) // undefined // } }}obj.init() This is very useful, no longer need to write me , self , _this , or bind .
4. The arrow function cannot be used with new
var Person = (name, age) => { this.name = name this.age = age}var p = new Func('John', 33) // error5. The argument cannot be used
var func = () => { console.log(arguments)}func(55) //For 5, the test in Firefox36 can output 55, and there seems to be no limit.
3. Summary
The above is the entire introduction to the arrow function in ES6. I hope it will be helpful to everyone. If you have any questions, please leave a message to discuss.