2.将正则的this存储下来,就是将当前指向的this用一个变量储存起来,在之后需要时直接引用这个变量即可指向我们保存下来的对象。
window.num = 2;function fn() {console.log(this.num);}const obj = {num: 1,shownum1: function() {fn(); //函数前面没有对象,指向window},shownum2: fn,shownum3: function() {console.log(this.num);},shownum4: function() {let _this = this;console.log(_this.num);},shownum5: function() {let _this = this;return function() {console.log(_this.num); //_this->obj}}}obj.shownum1(); //this->window 输出2obj.shownum2(); //this->obj 输出1obj.shownum3(); //this->obj 输出1obj.shownum4(); //this->obj 输出1obj.shownum5()(); //this->obj 输出1
3.new关键字 - 指向new出来的实例对象,构造函数的方法中外层的this都指向我们构造的实例对象
window.num = 10;function fn() {console.log(this.num);}fn(); //10 this->windownew fn(); //undefined this->实例对象
