20_改变this指向.html 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. /*
  12. 区别:
  13. 1.调用方式不同
  14. 2.call apply 直接调用修改后的方法 bind 不会调用方法 返回的是一个新的方法 需要重新调用
  15. 修改this指向
  16. 1.call(修改的this,参数1,参数2)
  17. 2.apply(修改的this,【参数1,参数2】)
  18. 3.bind(修改的this,参数1,参数2)()
  19. */
  20. // var person1 = {
  21. // name: 'zs',
  22. // age: 18,
  23. // eat: function(){
  24. // console.log(this)
  25. // }
  26. // }
  27. // person1.eat()
  28. var person2 = {
  29. name: 'lisi',
  30. age: 30
  31. }
  32. // person1.eat.call(person2)
  33. function xx(a,b){
  34. console.log(a,b,this)
  35. }
  36. xx(1,2)
  37. xx.call(person2,4,5)
  38. xx.apply(person2,[5,6])
  39. //bind不会调用函数 返回的是一个修改this指向之后的方法
  40. xx.bind(person2,8,9)()
  41. </script>
  42. </body>
  43. </html>