9.箭头函数.html 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <ul>
  10. <li>内容一</li>
  11. <li>内容二</li>
  12. <li>内容三</li>
  13. <li>内容四</li>
  14. </ul>
  15. <script>
  16. function fn() {
  17. console.log(this); // window
  18. console.log(arguments);
  19. }
  20. fn();
  21. /**
  22. * ES6中提供箭头函数
  23. * 普通函数:function fn() {} fn();
  24. * 箭头函数:() => {语句...};
  25. * 特点:
  26. * 1.普通函数中的this指向window,箭头函数的this指向指的是上级作用域
  27. * 2.箭头函数中 没有arguments 但是可以通过rest去替代
  28. * 3.普通函数中this指向可以修改 箭头函数中this指向不能修改
  29. * 4.箭头函数中若代码块中只有一条语句,可以省略代码块
  30. * 5.箭头函数没有办法使用new
  31. *
  32. */
  33. // let fn1 = ()=>{
  34. // console.log('这是一个箭头函数',arguments);
  35. // };
  36. // fn1();
  37. let fn2 = () => console.log("111111");
  38. fn2();
  39. let fn3 = (...a) => {
  40. console.log(...a);
  41. }
  42. fn3(43,44,56,78,90);
  43. // setTimeout(()=>{},1000)
  44. var list = document.querySelectorAll("ul li");
  45. for (var i = 0; i < list.length; i++) {
  46. list[i].onclick = function () {
  47. // console.log(this); // 当前对象
  48. setInterval(function () {
  49. console.log(this); // window
  50. }.bind(this), 1000);
  51. };
  52. // list[i].onclick = () => {
  53. // console.log(this);// window
  54. // }
  55. }
  56. function Fn4(name,age) {
  57. this.name = name;
  58. this.age = age;
  59. }
  60. var person = new Fn4('LiLi',19);
  61. console.log(person);
  62. let Person2 = (age) => {
  63. this.age = age;
  64. }
  65. var news = new Person2(10);
  66. console.log(news);
  67. </script>
  68. </body>
  69. </html>