18_this指向.html 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. <button id="btn">点击我</button>
  10. <script>
  11. // this 指向问题 this一般指向调用它的对象
  12. // 如果有事件绑定,this指向事件绑定的对象
  13. let btn = document.getElementById("btn");
  14. btn.onclick = function(){
  15. // function bar(){
  16. // console.log(this);
  17. // }
  18. // bar();
  19. let bar = () => {
  20. console.log(this);
  21. }
  22. bar();
  23. console.log(this);
  24. }
  25. // 普通函数中 this指向window对象 默认为winow调用
  26. // function foo(){
  27. // console.log(this);
  28. // // 内部函数中 this指向window对象
  29. // function bar(){
  30. // console.log(this);
  31. // }
  32. // bar();
  33. // }
  34. // foo();
  35. // let obj = {
  36. // name:"张三",
  37. // age:18,
  38. // sex:"男",
  39. // sayName(){
  40. // console.log(this);
  41. // // function bar(){
  42. // // console.log(this);
  43. // // }
  44. // // bar();
  45. // // 箭头函数中 this指向为当前所在作用域的this (箭头函数中没有this)
  46. // let bar = () => {
  47. // console.log(this);
  48. // }
  49. // bar();
  50. // }
  51. // }
  52. // obj.sayName();
  53. // this 指向是可以被修改的 通过call、 apply、 bind 方法可以修改this指向
  54. var userName = "李四"
  55. var obj = {
  56. userName:"张三",
  57. age:18,
  58. sex:"男"
  59. }
  60. function sayName(word){
  61. console.log(this.userName+"说"+word);
  62. }
  63. // call 方法可以修改this指向为obj对象 要执行的函数.call(修改后的this对象,参数1,参数2...)
  64. // sayName.call(obj);
  65. // sayName("你好");
  66. // 如果函数需要接收参数 call方法中从第二个参数开始传递参数
  67. // sayName.call(obj,"你好");
  68. // apply 方法可以修改this指向为obj对象 要执行的函数.apply(修改后的this对象,参数数组)
  69. // sayName.apply(obj,["你好"]);
  70. // bind 方法可以修改this指向为obj对象 要执行的函数.bind(修改后的this对象,参数1,参数2...)
  71. // bind 方法返回一个新的函数 并不是立即执行函数
  72. let bar = sayName.bind(obj,"你好");
  73. bar();
  74. </script>
  75. </body>
  76. </html>