JS ES6 Arrow Functions

<meta charset="UTF-8">
<script>
/**
 * ES6 allows defining functions using "arrows" (=>).
 * */
var f1 = v => v;
console.info (f1 ('f1'));
//Equivalent to
var f2 = function(v) {
  return v;
};
console.info(f2('f2'));

/**
 * if the arrow function takes no arguments or takes multiple arguments
 * uses a parenthesis to represent the parameter part.
 * */
var f1_1 = () => 5;
console.info (f1_1 ());
//Equivalent to
var f1_2 = function () {
  return 5;
};
console.info (f1_2 ());

var f2_1 = (a, b) => a + b;
console.info(f2_1(7,8));
//Equivalent to
var f2_2 = function f2_2(a, b) {
  return a + b;
};
console.info(f2_2(7,8));

/**
 * If the code block of an arrow function has more than one statement, enclose them in curly braces and return with a return statement.
 * Since curly braces are interpreted as code blocks, if the arrow function returns an object directly, you must put parentheses around the object.
 * Arrow functions can be combined with variable destructuring.
 * */
const f3_1 = ({ first, last }) => first + ' ' + last;
console.info(f3_1({first:'time',last:'city lord'}));
//Equivalent to
var f3_2 = function f3_1(_ref) {
  var first = _ref.first;
  var last = _ref.last;
  return first + ' ' + last;
};
console.info(f3_2({first:'Wu',last:'Zheran'}));

/**
 * Notes on use
 * There are several caveats for using arrow functions.
 * (1) The this object in the function body is the object where it is defined, not the object where it is used.
 * (2) It cannot be used as a constructor, that is, the new command cannot be used, otherwise an error will be thrown.
 * (3) You cannot use the arguments object, which does not exist in the function body. If you want to use it, you can use Rest parameters instead.
 * (4) The yield command cannot be used, so arrow functions cannot be used as Generator functions.
 * The immobilization pointed to by this is not because there is a mechanism for binding this inside the arrow function. The actual reason is that the arrow function does not have its own this at all, so the inner this is the this of the outer code block. Just because it doesn't have this, it can't be used as a constructor.
 * In addition to this, the following three variables do not exist in the arrow function, pointing to the corresponding variables of the outer function: arguments, super, new.target.
 * */
function f4_1() {
  setTimeout(() => {
    console.log('args:', arguments);
  }, 100);
}
f4_1(2, 4, 6, 8);
//Equivalent to
function f4_2() {
  var _arguments = arguments;
  setTimeout(function () {
    console.log('args:', _arguments);
  }, 100);
}
f4_2(2, 4, 6, 8);
</script>

 

Effect picture:

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326566733&siteId=291194637