The content of this article is about the format & this of arrow functions in js and the difference from ordinary functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
// ES5 var selected = allJobs.filter(function (job) { return job.isSelected(); }); // ES6 箭头函数 var selected = allJobs.filter(job => job.isSelected()); // ES6 $("#confetti-btn").click(event => { playTrumpet(); fireConfettiCannon(); });
1. To write a function with multiple parameters (or no parameters or default values or destructured parameters), add parentheses around the parameter list.
2. Arrow functions with blocks will not automatically return values. Please use return statement.
3. There is one thing to note when using arrow functions to create ordinary objects. Always enclose objects in parentheses:
Arrow functions do not have their own this value. Values inside this arrow functions are always inherited from the enclosing scope.
For methods that will be called using object.method() syntax, use non-arrow functions. These functions will get a meaningful this value from the caller. Everything else uses arrow functions.
{ ... addAll: function addAll(pieces) { var self = this; _.each(pieces, function (piece) { self.add(piece); }); }, ... } // ES6 { ... addAll: function addAll(pieces) { _.each(pieces, piece => this.add(piece)); }, ... }
There is another small difference between arrow and non-arrow functions: arrow functions do not have their own arguments object.
Ordinary functions:
1. When a function is called as a global function, this points to the global object
2. When a function is called as a method in an object, this points to the object
3. When a function is used as a constructor, this points to the new object that comes out of the constructor new
4. You can also change the point of this through call, apply, and bind
1. The arrow function does not have this, and the this inside the function The nearest non-arrow function from the parent, and cannot change the direction of this.
2. The arrow function does not have super
3. The arrow function does not have arguments
4. The arrow function does not have new.target binding.
5. New cannot be used.
6. There is no prototype.
7. Duplicate named parameters are not supported.
Related recommendations:
Answers to this question in ES6 arrow functions
##Detailed explanation of JavaScript arrow functions
The above is the detailed content of An explanation of the format & this of arrow functions in js and the difference from ordinary functions. For more information, please follow other related articles on the PHP Chinese website!