19.修改this指向.html 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. <script>
  10. // 单行注释
  11. /**
  12. * 多行注释
  13. */
  14. /**
  15. * 修改this指向:
  16. * call apply
  17. */
  18. function fn1(x,y) {
  19. var sum = x + y;
  20. console.log(sum);
  21. console.log(this);
  22. console.log(this.name);
  23. }
  24. var obj = {
  25. name: "Lucy"
  26. }
  27. // fn1(1,2);
  28. // xxx.call(指向哪就传哪,参数1,参数2...)
  29. fn1.call(obj,3,4)
  30. function fn2(x,y) {
  31. var sum = x * y;
  32. console.log(sum); // 6
  33. console.log(this); // window
  34. console.log(this.age);
  35. }
  36. var obj2 = {
  37. name: "孙悟空",
  38. age: 20
  39. }
  40. // fn2(2,3)
  41. // xxx.apply(指向哪就传哪,[参数一,参数二...])
  42. fn2.apply(obj2,[4,5])
  43. function fn3(a,b) {
  44. var sum = b - a;
  45. console.log(sum);
  46. console.log(this);
  47. console.log(this.name);
  48. }
  49. var obj3 = {
  50. name: "猪八戒",
  51. age: 22
  52. }
  53. // fn3(6,7)
  54. // xxx.bind(指向哪就传哪,参数1,参数2)()
  55. fn3.bind(obj3,4,9)();
  56. </script>
  57. </body>
  58. </html>