2.将正则的this存储下来,就是将当前指向的this用一个变量储存起来,在之后需要时直接引用这个变量即可指向我们保存下来的对象。

    1. window.num = 2;
    2. function fn() {
    3. console.log(this.num);
    4. }
    5. const obj = {
    6. num: 1,
    7. shownum1: function() {
    8. fn(); //函数前面没有对象,指向window
    9. },
    10. shownum2: fn,
    11. shownum3: function() {
    12. console.log(this.num);
    13. },
    14. shownum4: function() {
    15. let _this = this;
    16. console.log(_this.num);
    17. },
    18. shownum5: function() {
    19. let _this = this;
    20. return function() {
    21. console.log(_this.num); //_this->obj
    22. }
    23. }
    24. }
    25. obj.shownum1(); //this->window 输出2
    26. obj.shownum2(); //this->obj 输出1
    27. obj.shownum3(); //this->obj 输出1
    28. obj.shownum4(); //this->obj 输出1
    29. obj.shownum5()(); //this->obj 输出1

    3.new关键字 - 指向new出来的实例对象,构造函数的方法中外层的this都指向我们构造的实例对象

    1. window.num = 10;
    2. function fn() {
    3. console.log(this.num);
    4. }
    5. fn(); //10 this->window
    6. new fn(); //undefined this->实例对象