场景1、 函数直接调用时

  • this指向全局变量,node就是global,js就是window
  • 严格模式下就是undefined ```javascript // eg one 普通调用 function test () { console.log(this) } test() ; // undefined 或 Window(Object)

// eg two 普通函数调用嵌套一层普通函数调用 function son () { console.log(this) } function father () { son(); } father(); // undefined 或 Window(Object)

  1. <a name="ketXe"></a>
  2. ## 场景2、 函数被其他对象调用时候
  3. - 就是`obj.fun()`被谁点了,this就是指向谁,要注意是**执行的时候**,不是定义的时候
  4. - 操作访问符访问方法时,方法会隐式绑定前面的对象
  5. ```javascript
  6. // eg one 正常一个对象里面的函数
  7. const father = {
  8. type: 'person',
  9. buy: function() {
  10. console.log(this)
  11. }
  12. }
  13. father.buy(); // {type: 'person', buy: ƒ}
  14. // eg two 对象嵌套里面的函数
  15. const father = {
  16. type: 'person',
  17. cat: {
  18. type: 'animal',
  19. buy: function() {
  20. console.log(this)
  21. }
  22. }
  23. }
  24. father.cat.buy(); //{type: 'animal', buy: ƒ}
  25. // eg three 监听的函数
  26. const father = {
  27. buy: function() {
  28. console.log(this)
  29. }
  30. }
  31. window.addEventListener('scroll', father.buy); // undefined 或 Window(Object), 因为执行的时候是自然执行的
  32. //eg four 奇怪的语法
  33. const father = {
  34. buy: function() {
  35. console.log(this)
  36. }
  37. }
  38. (1, father.buy)(); // undefined 或 Window(Object), 因为执行的时候是自然执行的
  • 一个额外语法: var a = (1, 2); 这里括号里面会返回第二个值

场景3、 new一个实例的时候

  • 就是指向new出来的实例 ```javascript // eg one function Person(aa) { console.log(this) } let teacher = new Person(‘aa’); // Person {} 这里会打印出构造函数,实际上this就是指向新实例的,可以参考可以new过程发生的事情

// new的过程 // 1. 在内存中创建一个新的对象 // 2. 把这个对象的prototype指向这个构造函数的prototype // 3. 然后把这个this指向新对象的this // 4. 然后执行里面的代码赋值 // 5. 如果return非空对象,则正常return;如果没有return,则返回新创建的这个对象

  1. <a name="v5iJP"></a>
  2. ## 场景4、call,apply,bind
  3. - call,apply
  4. - 改变this的指向,接受两个参数,一个是this的指向,一个是接受参数
  5. - 绑定了函数的this之后立刻执行
  6. ```javascript
  7. const obj = {name: 'one'}
  8. function test (first, second) {
  9. console.log(first, second);
  10. console.log(this)
  11. }
  12. test.call(obj, 1, 2); // 1 2 {name: 'one'}
  13. test.apply(obj, [1, 2]); // 1 2 {name: 'one'}
  • bind
    • 给你返回一个绑定了this的函数
    • bind直接传参不能动态传参 ```javascript // eg one const obj = {name: ‘one’} function test (first, second) { console.log(this) } const fun = test.bind(obj, 1, 2); fun(); // 1 2 {name: ‘one’}
  1. <a name="iHX28"></a>
  2. ## 场景5、箭头函数
  3. - this指向离我的**定义时候非箭头函数的上下文**
  4. ```javascript
  5. // eg one
  6. function one () {
  7. console.log(this); // {name: 'test', one: ƒ}
  8. // one才是arrow的定义时上下文
  9. const arrow = () => {console.log(this)} // {name: 'test', one: ƒ}
  10. function two () {
  11. console.log(this); // Window
  12. arrow();
  13. }
  14. two();
  15. }
  16. const test = {name: 'test'};
  17. test.one = one;
  18. test.one();
  19. // eg two
  20. const arrow = () => {console.log(this)};
  21. const obj = {name: 'joe'};
  22. arrow.call(obj); // window