1. 方法调用

  1. <script>
  2. var age = 38;
  3. var obj = {
  4. age: 18,
  5. getAge: function () {
  6. console.log(this.age);
  7. }
  8. };
  9. // this指向了谁? 指向了obj
  10. obj.getAge();
  11. var fn = obj.getAge;
  12. // this指向了谁 指向widow
  13. fn();
  14. </script>

2.函数调用

  1. <script>
  2. var age = 38;
  3. var obj = {
  4. age: 18,
  5. getAge: function () {
  6. var fn = function () {
  7. console.log(this.age);
  8. };
  9. // this指向了谁
  10. console.log(this);
  11. fn();
  12. }
  13. };
  14. obj.getAge();
  15. </script>

3.构造函数

  1. <script>
  2. function MadeCat(name,age) {
  3. // this指向了谁? //Madecat
  4. console.log(this);
  5. this.name = name;
  6. this.age = age;
  7. }
  8. var cat = new MadeCat('小白',2);
  9. </script>

4. call apply bind

  1. <script>
  2. // 1. 声明两个变量和一个函数
  3. var username = '张三';
  4. var age = 18;
  5. function say(provice, city) {
  6. console.log('this=', this);
  7. console.log(`我来自${provice}${city}`);
  8. console.log(`我叫${this.username},今年${this.age}岁`);
  9. }
  10. // 2. 创建一个对象
  11. var person = {
  12. username: 'laohu',
  13. age: 23
  14. };
  15. var persons = {
  16. username: 'xb',
  17. age: 23
  18. };
  19. say('广东', '深圳');
  20. /**
  21. * 使用call改变this的指向
  22. * @param person this要指向的对象
  23. * @param '广西','贵港' 实参,可以传多个
  24. */
  25. say.call(person, '广西', '贵港');
  26. /**
  27. * 使用apply改变this的指向
  28. * @param person this要指向的对象
  29. * @param ['广西','贵港'] 实参,是个数组,所有参数都放入数组内
  30. */
  31. say.apply(persons, ['hn', 'xy']);
  32. </script>
  33. <script>
  34. // 1. 声明两个变量和一个函数
  35. var username = '张三';
  36. var age = 18;
  37. function say(provice, city) {
  38. console.log('this=', this);
  39. console.log(`我来自${provice}${city}`);
  40. console.log(`我叫${this.username},今年${this.age}岁`);
  41. }
  42. // 2. 创建一个对象
  43. var person = {
  44. username: '老胡',
  45. age: 100
  46. };
  47. say('广东', '深圳');
  48. /**
  49. * 3.使用bind改变this的指向
  50. * - 使用bind后会获得一个新的函数,新的函数具备跟原函数一样的功能
  51. * - 新函数的this指向发生了改变
  52. */
  53. var say2 = say.bind(person);
  54. // 调用新函数,跟原函数一模一样,不过this发生了改变
  55. say2('广西', '贵港');
  56. </script>