21_改变this指向.html 987 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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,1,2)
  38. xx.apply(person2,[3,4])
  39. xx.bind(person2,7,8)()
  40. </script>
  41. </body>
  42. </html>