arrow-function.js 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var square = x => x * x;
  2. var user = {
  3. name: 'Pedro',
  4. // Arrow functions do not bind the 'this' keyword
  5. sayHi: () => {
  6. console.log(`Hi! I am ${this.name}`);
  7. },
  8. // Traditional functions do bind the 'this' keyword
  9. sayHiAlt: function() {
  10. console.log(`Hi! I am ${this.name}`);
  11. },
  12. /* This could also be written like this:
  13. sayHiAlt() {
  14. console.log(`Hi! I am ${this.name}`);
  15. }
  16. */
  17. // Arrow functions also don't bind the arguments array
  18. printArgs: () => {
  19. // This is not a local arguments array, but global arguments array
  20. // be careful!!
  21. console.log(arguments);
  22. },
  23. printArgsAlt() {
  24. // This is a local arguments array from function call
  25. console.log(arguments);
  26. }
  27. };
  28. user.sayHi();
  29. user.sayHiAlt();
  30. // Global args get printed
  31. user.printArgs(3, 'sad tigers', 3, ' wheat dishes');
  32. // { '0': 3, '1': 'sad tigers', '2': 3 ... } local arguments array as object
  33. user.printArgsAlt(3, 'sad tigers', 3, ' wheat dishes');
  34. console.log(square(9));